[英]C# Enumerate Regex Matches
What is the best way to enumerate a regex-replacement in C#. 枚举C#中的正则表达式替换的最佳方法是什么。
For example if I wanted every "<intent-filter" match to be replaced by "<intent-filter android:label=label#" . 例如,如果我希望将每个“ <intent-filter”匹配项替换为“ <intent-filter android:label = label#” 。 The # sign is a incremental digit. #号是一个增量数字。 What would be the best way to code it? 最好的编码方式是什么?
You can use an incremented counter in the anonymous method specified as the MatchEvaluator
callback. 您可以在指定为MatchEvaluator
回调的匿名方法中使用递增计数器。 The (?<=…)
is positive lookbehind; (?<=…)
是正向后看; it is matched by the regex evaluator, but not removed. 它与regex评估程序匹配,但未删除。
string input = "a <intent-filter data=a /> <intent-filter data=b />";
int count = 0;
string result = Regex.Replace(input, @"(?<=\<intent-filter)",
_ => " android:label=label" + count++);
Don't bother with Regexes for this one. 不要为正则表达式而烦恼。 Do something along the lines of: 采取以下行动:
var pieces = text.Split(new string[] { "xx" });
var sb = new StringBuilder();
var idx = 0;
foreach (var piece in pieces)
{
sb.Append(piece);
sb.Append(" android:label=label");
sb.Append(idx);
}
// oops, homework assignment: remove the last "<intent-filter android:label=label#"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.