开发者

Replace String.Replace with Regex.Replace

OLD:

private string Check_long(string input)
{
    input = input.Replace("cool", "supercool");
    input = input.Replace("cool1", "supercool1");
    input = input.Replace("cool2", "supercool2");
    input = input.Replace("cool3", "supercool3");
    return input;
}

NEW:

private string Check_short(string input)
{    
    input = Regex.Replace(input开发者_Python百科, "cool", "supercool", RegexOptions.IgnoreCase);
    input = Regex.Replace(input, "cool1", "supercool1", RegexOptions.IgnoreCase);
    input = Regex.Replace(input, "cool2", "supercool2", RegexOptions.IgnoreCase);
    input = Regex.Replace(input, "cool3", "supercool3", RegexOptions.IgnoreCase);
    return input;
}

The old solution with String.Replace was working just fine. But it didn't support case-insensitivity. So I had to check for Regex.Replace, but now it won't work. Why is that ?


Your new code should work fine. Note that you can also retain the case of your input using a capture group:

private string Check_short(string input)
{    
    return Regex.Replace(input, "(cool)", "super$1", RegexOptions.IgnoreCase);
}


working fine here:

        string input = "iiii9";
        input = Regex.Replace(input, "IIII[0-9]", "jjjj" , RegexOptions.IgnoreCase);
        label1.Text = input;

output

jjjj


Regex do not work the say way that string.replace does. You need to build the regex around what you are trying to filter for.

private string Check_short(string input)
{    
    input = Regex.Replace(input, ".*(cool).*", "supercool", RegexOptions.IgnoreCase);
    return input;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜