【发布时间】:2015-04-23 09:17:16
【问题描述】:
我有字符串string testString = "Test id=10 sgdsdg id=15"
我想将 10 替换为 100 和 15 替换为 150
我写了
string testString = "Test id=10 sgdsdg id=15";
Regex testregex = new Regex("(?<=id=)\\d+");
MatchCollection matchCollection = testregex.Matches(testString);
foreach (Match match in matchCollection)
{
if (match.Value.Equals("10"))
{
match.Result("100");
}
if (match.Value.Equals("15"))
{
match.Result("150");
}
}
我不想使用跟随,因为对于每场比赛我都必须检查一些情况。喜欢身份证
Match.Value =10 Match.Value =12
testregex .Replace(testString , m => oldNewValueMapping[m.Value])
【问题讨论】:
-
Regex.Replace(yourString, @"(?<=id=)(\d+)", "$10"); -
但它会将 10 和 15 替换为相同的 10 美元,你认为这里的 10 美元是什么?
-
$1将引用正则表达式中的第一个组,对于第一个匹配项,它将返回10。正则表达式引擎将再次尝试匹配字符串,并且第二次返回15,它将再次存储在$1中。问题是执行$10将指示正则表达式引擎检查不存在的第10 个匹配组。我在下面提出了解决此问题的方法。 -
能否请您写下整个代码。我试过了,但它不起作用。
标签: c# asp.net regex asp.net-mvc c#-4.0