更换与string.replace与Regex.Replacereplace、string、Replace、Regex

由网友(π 浅易)分享简介:旧 private string Check_long(string input){input = input.Replace("cool", "supercool");input = input.Replace("cool1", "supercool1");input = input.Replace("cool...

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;
}

private string Check_short(string input)
{    
    input = Regex.Replace(input, "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;
}

旧的解决方案与string.replace 是工作就好了。但它不支持不区分大小写。因此,我不得不检查 Regex.Replace ,但现在它不会工作。这是为什么呢?

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 ?

推荐答案

您新的code应该很好地工作。请注意,您也可以使用捕获组保留您输入的情况下:

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);
}
阅读全文

相关推荐

最新文章