【问题标题】:C# Regex for getting all possible matches [duplicate]用于获取所有可能匹配项的 C# 正则表达式 [重复]
【发布时间】:2018-09-07 19:33:39
【问题描述】:

我想提取这个正则表达式的所有出现

\d{7,8}

(每个长度为 7 或 8 的数字)

输入可能是这样的

asd123456789bbaasd

我想要的是一个数组:

["1234567", "12345678", "2345678", "23456789"]

长度为 7 或 8 的数字的所有可能出现情况。

Regex.Matches 工作方式不同,它返回所有连续出现的匹配项......["12345678"]

有什么想法吗?

【问题讨论】:

  • 能否请您附上您的code?让你更容易给出准确简洁的答案
  • 正则表达式不是为此而设计的。你必须自己做排列
  • 你需要匹配一个数字,其余的都在前面。
  • @elgonzo 这行不通,因为它会丢失从同一索引开始的长度为 7 和 8 的数字。然后,您需要将正则表达式分成 2 个步骤。

标签: c# regex


【解决方案1】:

对于重叠匹配,您需要capture inside a lookahead

(?=(\d{7}))(?=(\d{8})?)

See this demo at regex101

  • (?=(\d{7})) 第一个 capturing group 是强制性的,将捕获任何 7 位数字
  • (?=(\d{8})?)第二个捕获组是optional(在同一位置触发)

因此,如果有 7 位匹配,它们将在组 (1) 中,如果 8 位匹配,则在组 (2) 中。在 .NET 正则表达式中,您可能可以使用 one name for both groups

只有在前面有 8 个时才能获得 7 位匹配,请在 (\d{8}) like in this demo 之后删除 ?

【讨论】:

  • 获取所有第 1 组和第 2 组值,删除空值,它将按预期工作。
  • 太棒了!这就是我需要的
【解决方案2】:

不是你真正要求的,但最终结果是。

using System;
using System.Collections.Generic;

namespace _52228638_ExtractAllPossibleMatches
{
    class Program
    {

        static void Main(string[] args)
        {
            string inputStr = "asd123456789bbaasd";
            foreach (string item in GetTheMatches(inputStr))
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();
        }

        private static List<string> GetTheMatches(string inputStr)
        {
            List<string> retval = new List<string>();
            int[] lengths = new int[] { 7, 8 };
            for (int i = 0; i < lengths.Length; i++)
            {
                string tmp = new System.Text.RegularExpressions.Regex("(\\d{" + lengths[i] + ",})").Match(inputStr.ToString()).ToString();
                while (tmp.Length >= lengths[i])
                {
                    retval.Add(tmp.Substring(0, lengths[i]));
                    tmp = tmp.Remove(0, 1);
                }
            }
            return retval;
        }
    }
}

【讨论】:

    猜你喜欢
    • 2010-10-12
    • 1970-01-01
    • 2013-05-09
    • 2016-10-28
    • 2011-10-02
    • 2010-11-16
    • 2015-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多