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, "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 ?
用字符串表示的旧溶液。替换工作还不错。但它不支持病例敏感性。所以我必须检查Regex。替换,但现在不行。这是为什么呢?
3 个解决方案
#1
13
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);
}
#2
5
working fine here:
在这里工作正常:
string input = "iiii9";
input = Regex.Replace(input, "IIII[0-9]", "jjjj" , RegexOptions.IgnoreCase);
label1.Text = input;
output
输出
jjjj
#3
-2
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.
Regex不会以那个字符串的方式工作。取代。您需要围绕您要筛选的内容构建regex。
private string Check_short(string input)
{
input = Regex.Replace(input, ".*(cool).*", "supercool", RegexOptions.IgnoreCase);
return input;
}
#1
13
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);
}
#2
5
working fine here:
在这里工作正常:
string input = "iiii9";
input = Regex.Replace(input, "IIII[0-9]", "jjjj" , RegexOptions.IgnoreCase);
label1.Text = input;
output
输出
jjjj
#3
-2
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.
Regex不会以那个字符串的方式工作。取代。您需要围绕您要筛选的内容构建regex。
private string Check_short(string input)
{
input = Regex.Replace(input, ".*(cool).*", "supercool", RegexOptions.IgnoreCase);
return input;
}