非常に基本的な質問ですが、なぜ機能しないのかわかりません。「And」を「And」、「and」などの任意の方法で記述できるコードがあり、「、」に置き換えたい
私はこれを試しました:
and.Replace("and".ToUpper(),",");
しかし、これは機能していません。これを行う、または機能させる他の方法はありますか?
正規表現クラスをチェックする必要があります
http://msdn.microsoft.com/en-us/library/xwewhkd1.aspx
using System.Text.RegularExpressions;
Regex re = new Regex("\band\b", RegexOptions.IgnoreCase);
string and = "This is my input string with and string in between.";
re.Replace(and, ",");
words = words.Replace("AND", ",")
.Replace("and", ",");
または、RegExを使用します。
このReplace
メソッドは、置換が表示されている文字列を返します。元の文字列は変更されません。あなたはの線に沿って何かを試してみるべきです
and = and.Replace("and",",");
遭遇する可能性のある「および」のすべてのバリエーションに対してこれを行うことができます。または、他の回答が示唆しているように、正規表現を使用することもできます。
いくつかの単語に含まれている場合は注意が必要だと思いand
ます"this is sand and sea"
。「砂」という言葉は、置き換えの影響を受けてはなりません。
string and = "this is sand and sea";
//here you should probably add those delimiters that may occur near your "and"
//this substitution is not universal and will omit smth like this " and, "
string[] delimiters = new string[] { " " };
//it result in: "this is sand , sea"
and = string.Join(" ",
and.Split(delimiters,
StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Length == 3 && s.ToUpper().Equals("AND")
? ","
: s));
私もこのようなsmthを追加します:
and = and.Replace(" , ", ", ");
したがって、出力:
this is sand, sea
静的Regex.Replace()
メソッドを使用するには、次の方法を試してください。
and = System.Text.RegularExpressions.Regex.Replace(and,"(?i)and",",");
「(?i)」を使用すると、次のテキスト検索で大文字と小文字が区別されなくなります。
http://msdn.microsoft.com/en-us/library/yd1hzczs.aspx
http://msdn.microsoft.com/en-us/library/xwewhkd1(v=vs.100).aspx