首页 > 解决方案 > C# Regex for getting all possible matches

问题描述

I'd like to extract all the occurences of this regex

\d{7,8}

(every number that has 7 or 8 length)

The input cuould be something like

asd123456789bbaasd

what I want is an array with:

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

all the possible occurencies of a number that has 7 or 8 lenth.

Regex.Matches works diferent, it returns all the consecutive occurencies of matches.... ["12345678"]

Any idea?

标签: c#regex

解决方案


对于重叠匹配,您需要在前瞻中捕获

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

在 regex101 看到这个演示

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

因此,如果有 7 位匹配,它们将在组(1)中,如果 8 位匹配,则在组(2)中。在 .NET Regex 中,您可能可以为两个组使用一个名称

要仅在前面有 8 个时才获得 7 位匹配,请在此演示中?删除after 。(\d{8})


推荐阅读