基于this question正则表达式\d+(?:-\d+)+
将与10-3-1
和5-0
匹配。
示例:
This is 10-3-1 my string
执行匹配和反转后,我希望它是这样的:
This is 1-3-10 my string
请注意,10-3-1应该变为1-3-10而不是正常的字符串反转,这将导致1-3-01。
答案 0 :(得分:2)
基本算法是:
"10-3-1"
["10","3","1"]
["1","3","10"]
"1-3-10"
答案 1 :(得分:1)
虽然这里回答的问题是一段带有略微修改的正则表达式的代码:
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));
}