40
string sentence = "We know it contains 'camel' word.";
// Camel can be in different cases:
string s1 = "CAMEL";
string s2 = "CaMEL";
string s3 = "CAMeL";
// ...
string s4 = "Camel";
// ...
string s5 = "camel";

左の文字列string.Replaceがサポートされていないにもかかわらず、文中の「ラクダ」を「馬」に置き換える方法は?ignoreCase

4

10 に答える 10

56

正規表現を使用します。

var regex = new Regex( "camel", RegexOptions.IgnoreCase );
var newSentence = regex.Replace( sentence, "horse" );

もちろん、これは camel を含む単語にも一致しますが、それが必要かどうかは明確ではありません。

完全一致が必要な場合は、カスタム MatchEvaluator を使用できます。

public static class Evaluators
{
    public static string Wrap( Match m, string original, string format )
    {
        // doesn't match the entire string, otherwise it is a match
        if (m.Length != original.Length)
        {
            // has a preceding letter or digit (i.e., not a real match).
            if (m.Index != 0 && char.IsLetterOrDigit( original[m.Index - 1] ))
            {
                return m.Value;
            }
            // has a trailing letter or digit (i.e., not a real match).
            if (m.Index + m.Length != original.Length && char.IsLetterOrDigit( original[m.Index + m.Length] ))
            {
                return m.Value;
            }
        }
        // it is a match, apply the format
        return string.Format( format, m.Value );
    }
} 

次のようにスパンで一致をラップするために、前の例で使用されます。

var regex = new Regex( highlightedWord, RegexOptions.IgnoreCase );
foreach (var sentence in sentences)
{
    var evaluator = new MatchEvaluator( match => Evaluators.Wrap( match, sentence, "<span class='red'>{0}</span>" ) );
    Console.WriteLine( regex.Replace( sentence, evaluator ) );
}
于 2011-05-17T02:21:57.110 に答える
3

StringComparisonその便利さのために利用するOrdinalIgnoreCase

    string sentence = "We know it contains 'camel' word."; 
    string wordToFind = "camel";
    string replacementWord = "horse";

    int index = sentence.IndexOf(wordToFind , StringComparison.OrdinalIgnoreCase)
    // Did we match the word regardless of case
    bool match = index >= 0;

    // perform the replace on the matched word
    if(match) {
        sentence = sentence.Remove(index, wordToFind.Length)
        sentence = sentence.Insert(index, replacementWord)
    }

ignoreCase()確かに、C#の文字列クラスにJavaのようなメソッドがあればいいでしょう。

于 2012-09-21T19:55:53.347 に答える
2

String.IndexOf を使用することもできます

http://msdn.microsoft.com/en-us/library/system.string.indexof.aspx

この方法で行うと、RegExpressions を使用するよりもわずかに優れたパフォーマンスが得られる可能性があります (この単純な .Net 関数呼び出しは、実際の乱雑な RegEx を抽象化し、十分な余地を提供しませんが、直感的ではなく、台無しにするのが簡単なので、私はそれらを嫌います)。エラー)、しかしそれはおそらくあなたにとっては問題ではありません; 最近のコンピューターは本当に速いですよね?:) StringComparison オブジェクトを受け取る IndexOf のオーバーロードを使用すると、オプションで大文字と小文字を区別することができます。また、IndexOf は指定された位置からの最初の出現を返すため、複数の出現がある文字列を処理するループをコーディングする必要があります。

于 2011-05-17T03:51:24.247 に答える
1
    public static string CustomReplace(string srcText, string toFind, string toReplace, bool matchCase, bool replace0nce)
    {
        StringComparison sc = StringComparison.OrdinalIgnoreCase;
        if (matchCase)
            sc = StringComparison.Ordinal;

        int pos;
        while ((pos = srcText.IndexOf(toFind, sc)) > -1)
        {
            srcText = srcText.Remove(pos, toFind.Length);
            srcText = srcText.Insert(pos, toReplace);

            if (replace0nce)
                break;
        }

        return srcText;
    }
于 2013-11-01T19:28:45.010 に答える