开发者

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:

  1. Extract the match from the string. "10-3-1"
  2. Split the match into a segments by the "-" character.
  3. You now have a list of elements. ["10","3","1"]
  4. Reverse the list. ["1","3","10"]
  5. Join the elements of the array with the "-" character. "1-3-10"
  6. 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));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜