正規表現でテキストを置換する方法
正規表現の置換を使ってテキスト内のパターンを検索・置換します。キャプチャグループの参照も利用できます。
问题
テキスト内のパターンをすべて置換する必要があり、置換後の文字列でマッチした部分を再利用したい場合もあります。
前提条件
- 正規表現パターンの理解
- キャプチャグループに関する知識
ステップ
-
1. Define the search pattern
Write a regex that matches the text you want to replace. Use capture groups for parts you want to reuse in the replacement. The g flag is needed to replace all occurrences; without it, only the first match is replaced.
入力pattern: (\w+)@(\w+)输出captures name and domain -
2. Define the replacement
The replacement can be a literal string or a function. Use $1, $2, etc. to reference capture groups in the replacement string. A function receives match details and can return dynamic replacements based on the matched content.
入力replace with: $2.$1输出swaps name and domain -
3. Execute and verify
Run the replacement and inspect the output. Check that all intended matches were replaced and that no unintended matches were affected. If the result is wrong, adjust the pattern or replacement and retry.
入力[email protected] → example.alice输出verified
期待される結果
置換仕様に従って、マッチしたパターンがすべて置換されたテキスト。
よくあるエラー
- Only first occurrence replaced
- Add the g (global) flag to replace all occurrences. Without g, replace only changes the first match.
- Replacement includes literal $1 instead of captured text
- Ensure the replacement string uses the correct syntax for capture group references. Different languages use $1 vs \1.
トラブルシューティング指引
- If too many replacements occur, make the pattern more specific.
- Use a replacement function for complex logic that cannot be expressed as a simple string.
セキュリティ上の制限
- Regex replacement on untrusted input can be vulnerable to ReDoS. Use safe patterns and consider a timeout.