如何编写可以捕获每个匹配的编号计数的替换模式? [英] How can you write a substitution pattern that can capture the numbered count for each match ?
问题描述
如何编写可以捕获每个匹配的编号计数的替换模式?
例如,如果我希望字符串中的第一个问号被替换为?1,第二个问号应该是替换为?2等等。
然后,作为示例,如果我将使用以下字符串作为输入:
" abc?防范? ijk? 123? 55555? 987"
然后在替换之后,得到的输出字符串应该变成这样:
" abc? 1 defgh? 2 ijk? 3 123? 4 55555? 5 987"
/ Tom
我找到了一种方法,通过使用具有MatchEvaluator委托方法的类来跟踪编号的事件,但是没有任何类型的替换模式可以用来以更直接的方式实现同样的事情吗?
这是我到目前为止找到的唯一解决方案:
公共类MatchEvaluatorConcatenatingNumberedOccurrenceAfterEachMatch
{
private int numbersOccurrence = 0;
公共字符串concatenateNumberedOccurrenceAfterEachMatch(匹配匹配)
{
numbersOccurrence ++; < br>
返回" " + match.Groups [1] .Value + numberedOccurrence +" " ;;
}
}
[测试]
public void TestConcatenateNumberedOccurrenceAfterEachMatch()
{
string inputString =" abc?防范? ijk? 123? 55555? 987" ;; $
MatchEvaluatorConcatenatingNumberedOccurrenceAfterEachMatch myMatchEvaluator = new MatchEvaluatorConcatenatingNumberedOccurrenceAfterEachMatch();
string substitutedString = Regex.Replace(
inputString,
" (\\?)",
myMatchEvaluator.concatenateNumberedOccurrenceAfterEachMatch // MatchEvaluator委托
);
Assert.AreEqual(" abc?1 defgh ?2 ijk?3 123?4 55555?5 987",substituteString);
}
/ Tom
How can you write a substitution pattern that can capture the numbered count for each match ?
For example if I would want the first questionmark in a string become replaced with ?1 , and the second questionmark should be replaced with ?2 and so on.
Then, as an example, if I would use the following string as input:
"abc ? defgh ? ijk ? 123 ? 55555 ? 987"
then after the substitutions, the resulting output string should become this:
"abc ?1 defgh ?2 ijk ?3 123 ?4 55555 ?5 987"
/ Tom
I found a way of doing it by using a class with a MatchEvaluator delegate method that keeps track of the numbered occurrence, but is not there any kind of replacement pattern that can be used to achieve the same thing in a more straightforward way ?
This is the only solution I have found so far:
public class MatchEvaluatorConcatenatingNumberedOccurrenceAfterEachMatch
{
private int numberedOccurrence = 0;
public string concatenateNumberedOccurrenceAfterEachMatch(Match match)
{
numberedOccurrence++;
return " " + match.Groups[1].Value + numberedOccurrence + " ";
}
}
[Test]
public void TestConcatenateNumberedOccurrenceAfterEachMatch()
{
string inputString = "abc ? defgh ? ijk ? 123 ? 55555 ? 987";
MatchEvaluatorConcatenatingNumberedOccurrenceAfterEachMatch myMatchEvaluator = new MatchEvaluatorConcatenatingNumberedOccurrenceAfterEachMatch();
string substitutedString = Regex.Replace(
inputString,
" (\\?) ",
myMatchEvaluator.concatenateNumberedOccurrenceAfterEachMatch // MatchEvaluator delegate
);
Assert.AreEqual("abc ?1 defgh ?2 ijk ?3 123 ?4 55555 ?5 987", substitutedString);
}
/ Tom
这篇关于如何编写可以捕获每个匹配的编号计数的替换模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!