【问题标题】:Match a regex and reverse the matches within the target string匹配正则表达式并反转目标字符串中的匹配项
【发布时间】:2011-09-30 22:55:38
【问题描述】:

基于this question 正则表达式\d+(?:-\d+)+ 将匹配此10-3-15-0

例子:

This is 10-3-1 my string

执行匹配和反转后,我希望它是这样的:

This is 1-3-10 my string

请注意,10-3-1 应该变成 1-3-10,而不是正常的字符串反转,这会导致 1-3-01。

【问题讨论】:

  • 您还在寻找 C# 代码吗?

标签: c# regex string reverse


【解决方案1】:

基本算法是:

  1. 从字符串中提取匹配。 "10-3-1"
  2. 用“-”字符将匹配分割成段。
  3. 您现在有了一个元素列表。 ["10","3","1"]
  4. 反转列表。 ["1","3","10"]
  5. 用“-”字符连接数组的元素。 "1-3-10"
  6. 用新加入的字符串替换匹配项。

【讨论】:

  • OK 看起来不错,但是如果字符串包含多个匹配项怎么办?因为可能是这种情况。我想我可以使用 GroupCollection。
  • 是的,您只需为找到的每个匹配项执行这些步骤。
【解决方案2】:

虽然这里的问题得到了回答,但这是一段带有稍微修改的正则表达式的代码:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-08
    • 2023-03-13
    • 2012-06-05
    • 2013-12-25
    • 1970-01-01
    相关资源
    最近更新 更多