😸

[解決済み]Amazon Q(preview)で、使えない記号を削除するスクリプトを作った

2023/11/29に公開

記号を使うとエラーになるときがある

噂のAmazonQなのですが、使ってみると一発目からエラー出してしまいました。

Invalid input. Valid characters are A-Z a-z . , ? ! @ & : ; ( ) ' " -

だそうです・・・OMG

アンダースコアをハイフンに変えると教えてくれます。

補正用のスクリプト

ChatGPT4に作ってもらいました

Python

import re

# Input string to modify
original_string = "This is a test! @ with some allowed & unallowed * characters %"

allowed_chars = "A-Za-z.,?!@&:;()'\\" + '"'
regex = f'[^{allowed_chars}]'
cleaned_string = re.sub(regex, ' ', original_string)

print("original string:")
print(original_string)

print("cleaned string:")
print(cleaned_string)

出力はこうなるはず

original string:
This is a test! @ with some allowed & unallowed * characters %
cleaned string:
This is a test! @ with some allowed & unallowed   characters

Shell Script

#!/bin/bash

# Input string to modify
original_string="This is a test! @ with some allowed & unallowed * characters %"

# Define allowed characters, including the space character and escaping special characters
allowed_chars="A-Za-z.,?!@&:;()'\" "

# Use sed to remove characters not in the allowed list
# Here, the sed command is modified to include space in the allowed list
# and to escape characters that could be interpreted as special characters by sed
cleaned_string=$(echo "$original_string" | sed "s/[^$allowed_chars]//g")

echo "original string:"
echo "$original_string"

echo "cleaned string:"
echo "$cleaned_string"

Discussion