2

非常に基本的な質問ですが、なぜ機能しないのかわかりません。「And」を「And」、「and」などの任意の方法で記述できるコードがあり、「、」に置き換えたい

私はこれを試しました:

and.Replace("and".ToUpper(),",");

しかし、これは機能していません。これを行う、または機能させる他の方法はありますか?

4

5 に答える 5

6

正規表現クラスをチェックする必要があります

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, ",");
于 2012-09-21T00:50:34.300 に答える
2
words = words.Replace("AND", ",")
             .Replace("and", ",");

または、RegExを使用します。

于 2012-09-21T00:51:47.357 に答える
2

このReplaceメソッドは、置換が表示されている文字列を返します。元の文字列は変更されません。あなたはの線に沿って何かを試してみるべきです

and = and.Replace("and",",");

遭遇する可能性のある「および」のすべてのバリエーションに対してこれを行うことができます。または、他の回答が示唆しているように、正規表現を使用することもできます。

于 2012-09-21T00:54:47.757 に答える
2

いくつかの単語に含まれている場合は注意が必要だと思い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
于 2012-09-21T01:14:51.490 に答える
0

静的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

于 2012-09-21T00:56:19.017 に答える