C#正则表达式,用于获取所有可能的匹配项

时间:2018-09-07 19:33:40

标签: c# regex

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

\d{7,8}

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

输入内容应该是

  

asd123456789bbaasd

我想要的是一个数组:

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

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

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

有什么主意吗?

2 个答案:

答案 0 :(得分:5)

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

fprintf(fp, "The median: %lf \nThe average: %lf", median, avg);

See this demo at regex101

  • @Autowired private StudentService studentService; capturing group是必填项,它将捕获任何7位数字
  • @Resource private StudentService studentService; 第二个捕获组是optional(在同一位置触发)

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

要仅在前面有8个数字时获得7位数字的匹配,请将(?=(\d{7}))(?=(\d{8})?) 放在(?=(\d{7})) like in this demo之后。

答案 1 :(得分: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;
        }
    }
}
相关问题