一部には、質問のタイトルが実際に尋ねられている特定の質問よりもはるかに大きいため、一種の紛らわしい回答のグループです。読んだ後、ここですべての良いものを吸収することから数回の編集で答えが得られるかどうかわからないので、合計しようと思いました.
ここで述べた落とし穴を回避し、最も広く適用可能なソリューションを提供すると思われる拡張メソッドを次に示します。
public static string ReplaceCaseInsensitiveFind(this string str, string findMe,
string newValue)
{
return Regex.Replace(str,
Regex.Escape(findMe),
Regex.Replace(newValue, "\\$[0-9]+", @"$$$0"),
RegexOptions.IgnoreCase);
}
そう...
残念ながら、 @HA の3 つすべてに対するコメントEscape
は正しくありません。初期値でnewValue
ある必要はありません。
注:ただし、 「キャプチャされた値」マーカーのように見えるものの一部である場合$
は、挿入する新しい値で sをエスケープする必要があります。したがって、Regex.Replace 内の Regex.Replace の 3 つのドル記号 [原文ママ]。それがなければ、このようなものは壊れます...
"This is HIS fork, hIs spoon, hissssssss knife.".ReplaceCaseInsensitiveFind("his", @"he$0r")
エラーは次のとおりです。
An unhandled exception of type 'System.ArgumentException' occurred in System.dll
Additional information: parsing "The\hisr\ is\ he\HISr\ fork,\ he\hIsr\ spoon,\ he\hisrsssssss\ knife\." - Unrecognized escape sequence \h.
教えてください、正規表現に慣れている人は、正規表現を使用するとエラーが回避されると感じていることは知っていますが、私はまだ文字列のバイトスニッフィングに部分的に取り組んでいます (ただし、Spolsky on encodingsを読んだ後でのみ)。重要なユースケースを対象としています。「安全でない正規表現」については、Crockford を少し思い出します。必要なものを許可する正規表現を (運が良ければ) 書き込んでしまうことがよくありますが、意図せずに多くのことを許可してしまいます (例えば$10
、上記の newValue 正規表現で本当に有効な「キャプチャ値」文字列ですか?)。 . どちらの方法にも価値があり、どちらもさまざまな種類の意図しないエラーを助長します。多くの場合、複雑さを過小評価するのは簡単です。
その奇妙な$
エスケープ (そして、置換値で期待していたRegex.Escape
ようなキャプチャされた値のパターンをエスケープしなかった) は、しばらくの間私を怒らせました。$0
プログラミングは難しい (c) 1842