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

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

\d{7,8}

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

输入可能类似于

asd123456789bbaasd

我想要的是一个数组:

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

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

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

任何的想法?


手掌心
浏览 220回答 2
2回答

慕沐林林

对于重叠匹配,您需要在前瞻中捕获。(?=(\d{7}))(?=(\d{8})?)在 regex101 看到这个演示(?=(\d{7}))第一个捕获组是强制性的,将捕获任何 7 位数字(?=(\d{8})?)第二个捕获组是可选的(在同一位置触发)因此,如果有 7 位匹配,它们将在组(1)中,如果 8 位匹配,则在组(2)中。在 .NET Regex 中,您可能可以为两个组使用一个名称。要仅在前面有 8 个时才获得 7 位匹配,请在此演示中删除?after 。(\d{8})

天涯尽头无女友

不是您真正要求的,但最终结果是。using System;using System.Collections.Generic;namespace _52228638_ExtractAllPossibleMatches{&nbsp; &nbsp; class Program&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; static void Main(string[] args)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; string inputStr = "asd123456789bbaasd";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; foreach (string item in GetTheMatches(inputStr))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(item);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.ReadLine();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; private static List<string> GetTheMatches(string inputStr)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; List<string> retval = new List<string>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int[] lengths = new int[] { 7, 8 };&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < lengths.Length; i++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; string tmp = new System.Text.RegularExpressions.Regex("(\\d{" + lengths[i] + ",})").Match(inputStr.ToString()).ToString();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; while (tmp.Length >= lengths[i])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; retval.Add(tmp.Substring(0, lengths[i]));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tmp = tmp.Remove(0, 1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return retval;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP