Match a regex and reverse the matches within the target string
Based on this question Regex \d+(?:-\d+)+ will match this 10-3-1 and 5-0.
Example:
This is 10-3-1 my string
开发者_如何学JAVA
After performing the matching and reversing, I want it to be like this:
This is 1-3-10 my string
Notice that 10-3-1 should become 1-3-10 and not normal string reverse which would result in 1-3-01.
A basic algorithm would be:
- Extract the match from the string.
"10-3-1" - Split the match into a segments by the "-" character.
- You now have a list of elements.
["10","3","1"] - Reverse the list.
["1","3","10"] - Join the elements of the array with the "-" character.
"1-3-10" - Replace the match with newly joined string.
Although the question was answered here is a piece of code with a slightly modified regex:
var text = "This is 10-3-1 and 5-2.";
var re = new Regex(@"((?<first>\d+)(?:-(?<parts>\d+))+)");
foreach (Match match in re.Matches(text))
{
var reverseSequence = match
.Groups["first"]
.Captures.Cast<Capture>()
.Concat(match.Groups["parts"].Captures.Cast<Capture>())
.Select(x => x.Value)
.Reverse()
.ToArray();
text = text.Replace(match.Value, string.Join("-", reverseSequence));
}
加载中,请稍侯......
精彩评论