是否有不区分大小写的 string.Replace 替代方案? [英] Is there an alternative to string.Replace that is case-insensitive?
问题描述
我需要搜索一个字符串并将所有出现的 %FirstName%
和 %PolicyAmount%
替换为从数据库中提取的值.问题是 FirstName 的大小写不同.这阻止了我使用 String.Replace()
方法.我已经看到有关该主题的网页建议
I need to search a string and replace all occurrences of %FirstName%
and %PolicyAmount%
with a value pulled from a database. The problem is the capitalization of FirstName varies. That prevents me from using the String.Replace()
method. I've seen web pages on the subject that suggest
Regex.Replace(strInput, strToken, strReplaceWith, RegexOptions.IgnoreCase);
然而,由于某种原因,当我尝试用 $0
替换 %PolicyAmount%
时,替换从未发生.我认为这与美元符号是正则表达式中的保留字符有关.
However for some reason when I try and replace %PolicyAmount%
with $0
, the replacement never takes place. I assume that it has something to do with the dollar sign being a reserved character in regex.
我可以使用另一种方法来处理输入以处理正则表达式特殊字符吗?
Is there another method I can use that doesn't involve sanitizing the input to deal with regex special characters?
推荐答案
来自 MSDN
$0 - 替换与组号(十进制)匹配的最后一个子字符串."
From MSDN
$0 - "Substitutes the last substring matched by group number number (decimal)."
在 .NET 正则表达式中,组 0 始终是整个匹配项.对于文字 $,您需要
In .NET Regular expressions group 0 is always the entire match. For a literal $ you need to
string value = Regex.Replace("%PolicyAmount%", "%PolicyAmount%", @"$$0", RegexOptions.IgnoreCase);
这篇关于是否有不区分大小写的 string.Replace 替代方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!