如果您使用的是 .NET 正则表达式,那么您的表达式将起作用,因为捕获组将捕获其所有值。否则,您必须使用更棘手的正则表达式或分两步进行匹配,首先匹配{ ... }
组,然后匹配其中的元素。
棘手的正则表达式看起来像:
(?:{|\G(?!^),) # match a { or where the previous match ended followed by a ,
\s+ # space between elements
(\S+)\s+\(\d+\) # an element
(?=[^{]*}) # make sure it's eventually followed by a }
You can use that expression as it's written if you use the /x
flag (can also be set by adding (?x)
in the beginning of the expression).
The regex without the comments:
(?:{|\G(?!^),)\s+(\S+)\s+\(\d+\)(?=[^{]*})
This expression uses \G
which your regex flavor has to support.
Most modern regex flavors have it, including: Perl, PCRE (PHP/etc), .NET.
Note that such an expression isn't perfect. It would capture AAA
and BBB
in the following string for example:
{ AAA (1), BBB (23), CCC, something invalid here #¤% ))),,,,!! }
Altho that can be fixed if required (except for the counter).