我需要用一些值替换给定字符串中所有标记的字符串,例如:
"This is the level $levelnumber of the block $blocknumber."
我想把它翻译成:
"This is the level 4 of the block 2."
这只是一个例子。实际上,我在文本中有几个 $data 标记,需要在运行时将其更改为某些数据。我不知道什么 $data 标签会出现在字符串中。
我打算为此使用正则表达式,但正则表达式确实令人困惑。
我试过但没有成功(有多种双引号、无引号等变体):
public static ShowTags (string Expression)
{
var tags = Regex.Matches(Expression, @"(\$([\w\d]+)[&$]*");
foreach (var item in tags)
Console.WriteLine("Tag: " + item);
}
感谢任何帮助。
[编辑]
工作代码:
public static ReplaceTagWithData(string Expression)
{
string modifiedExpression;
var tags = Regex.Matches(Expression, @"(\$[\w\d]+)[&$]*");
foreach (string tag in tags)
{
/// Remove the '$'
string tagname = pdata.Remove(0, 1);
/// Change with current value
modifiedExpression.Replace(pdata, new Random().ToString()); //Random simulate current value
}
return modifiedExpression;
}
最佳答案
试试像 \$(?<key>[\w\d]+)
这样的东西反而。那里有很多正则表达式测试器,我建议找其中一个来轻松试用您的正则表达式。
然后,正如 Szymon 所建议的,您可以使用 Regex.Replace,但还有一种更高级的方法:
string result = Regex.Replace( s, pattern, new MatchEvaluator( Func ) );
string Func( Match m )
{
return string.Format( "Test[{0}]", m.Groups["key"].Value );
}
Func
对于它在字符串中找到的每个匹配项,上面将调用一次,允许您返回替换字符串。
关于c# - 将所有标记的字符串更改为另一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19304452/