文字列から英数字以外の文字を削除する 質問する

文字列から英数字以外の文字を削除する 質問する

次の文字列を指定の出力に変換したいと思います。

Input:  "\\test\red\bob\fred\new"
Output: "testredbobfrednew"

、、などの特殊文字を処理するソリューションは見つかりませんでした\r\n\b

基本的に、英数字以外のものをすべて削除したいだけです。私が試したことは次のとおりです...

Attempt 1: "\\test\red\bob\fred\new".replace(/[_\W]+/g, "");
Output 1:  "testedobredew"

Attempt 2: "\\test\red\bob\fred\new".replace(/['`~!@#$%^&*()_|+-=?;:'",.<>\{\}\[\]\\\/]/gi, "");
Output 2:  "testedobred [newline] ew"

Attempt 3: "\\test\red\bob\fred\new".replace(/[^a-zA-Z0-9]/, "");
Output 3:  "testedobred [newline] ew"

Attempt 4: "\\test\red\bob\fred\new".replace(/[^a-z0-9\s]/gi, '');
Output 4:  "testedobred [newline] ew"

複数のステップを踏むもう一つの試み

function cleanID(id) {
    id = id.toUpperCase();
    id = id.replace( /\t/ , "T");
    id = id.replace( /\n/ , "N");
    id = id.replace( /\r/ , "R");
    id = id.replace( /\b/ , "B");
    id = id.replace( /\f/ , "F");
    return id.replace( /[^a-zA-Z0-9]/ , "");
}

結果が出る

Attempt 1: cleanID("\\test\red\bob\fred\new");
Output 1: "BTESTREDOBFREDNEW"

実用的なソリューション:

Final Attempt 1: return JSON.stringify("\\test\red\bob\fred\new").replace( /\W/g , '');
Output 1: "testredbobfrednew"

ベストアンサー1

英数字以外の文字を削除する

以下は、入力文字列から英数字以外の文字を削除するための正しい正規表現です。

input.replace(/\W/g, '')

\Wは と同等であることに注意してください[^0-9a-zA-Z_]。これにはアンダースコア文字が含まれます。アンダースコアも削除するには、次のようにします。

input.replace(/[^0-9a-z]/gi, '')

入力が不正です

テスト文字列には英数字ではないさまざまなエスケープ文字が含まれているため、それらは削除されます。

文字列内のバックスラッシュを文字通りに解釈するには、エスケープする必要があります。

"\\test\\red\\bob\\fred\\new".replace(/\W/g, '')
"testredbobfrednew" // output

不正な文字列の処理

入力文字列を正しくエスケープできない場合 (なぜできないのでしょうか?)、または何らかの信頼できないソースや誤って構成されたソースからのものである場合は、次のようにします。

JSON.stringify("\\test\red\bob\fred\new").replace(/\W/g, '')
"testredbobfrednew" // output

文字列の json 表現には引用符が含まれていることに注意してください。

JSON.stringify("\\test\red\bob\fred\new")
""\\test\red\bob\fred\new""

しかし、置換正規表現によっても削除されます。

おすすめ記事