匹配正则表达式并反转目标字符串中的匹配

发布于 2024-11-18 22:07:40 字数 382 浏览 1 评论 0原文

基于这个问题正则表达式\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。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

弄潮 2024-11-25 22:07:40

基本算法是:

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

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.
书间行客 2024-11-25 22:07:40

尽管这里回答的问题是一段稍微修改了正则表达式的代码:

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

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));
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文