Match a regex and reverse the matches within the target string

我只是一个虾纸丫 提交于 2019-12-24 09:39:46

问题


Based on this question Regex \d+(?:-\d+)+ will match this 10-3-1 and 5-0.

Example:

This is 10-3-1 my string

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.


回答1:


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.



回答2:


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));
}


来源:https://stackoverflow.com/questions/6619398/match-a-regex-and-reverse-the-matches-within-the-target-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!