简体   繁体   English

正则表达式:恒星重复算符的所有格量词,即\\ d **

[英]Regex: possessive quantifier for the star repetition operator, i.e. \d**

From the GLib Reference Manual, section "Regular expression syntax" , subsection "Atomic grouping and possessive quantifiers": 在GLib参考手册的“正则表达式语法”部分 ,“原子分组和所有格修饰符”小节中:

Consider the pattern \\d+foo when applied to the string 123456bar : after matching all 6 digits and then failing to match "foo", the normal action of the matcher is to try again with only 5 digits matching the \\d+ item, and then with 4, and so on, before ultimately failing. 考虑将\\d+foo应用于字符串123456bar :匹配所有6位数字,然后不匹配“ foo”后,匹配器的正常操作是仅使用5位数字匹配\\ d +项目,然后再尝试,然后4,依此类推,直到最终失败。

If we use (?>\\d+)foo (called atomic grouping ) for the previous example, the matcher give up immediately on failing to match "foo" the first time. 如果在前面的示例中使用(?>\\d+)foo (称为原子分组 ),则匹配器在第一次不匹配“ foo”时会立即放弃。

When the subpattern for an atomic group is just a single repeated item, as in the example above, a simpler notation, called a "possessive quantifier" can be used: \\d++foo 如上例所示,当原子组的子模式仅是一个重复项时,可以使用一种更简单的表示法,称为“可能量词”: \\d++foo

My question is: is there any reason why there is no equivalent for the star ( * ) repetition operator? 我的问题是:星号( * )重复运算符没有等效的原因吗?

Example in Java: Java范例:

final String in = "123456";
// "plus" (+)
System.out.println(in.matches("\\d+"));     // true
System.out.println(in.matches("(?>\\d+)")); // true
System.out.println(in.matches("\\d++"));    // true
// "star" (*)
System.out.println(in.matches("\\d*"));     // true
System.out.println(in.matches("(?>\\d*)")); // true
System.out.println(in.matches("\\d**"));    // exception

The exception stack trace is: 异常堆栈跟踪为:

Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 3
\d**
   ^
    at java.util.regex.Pattern.error(Pattern.java:1713)
    at java.util.regex.Pattern.sequence(Pattern.java:1878)
    at java.util.regex.Pattern.expr(Pattern.java:1752)
    at java.util.regex.Pattern.compile(Pattern.java:1460)
    at java.util.regex.Pattern.<init>(Pattern.java:1133)
    at java.util.regex.Pattern.compile(Pattern.java:823)
    at java.util.regex.Pattern.matches(Pattern.java:928)
    at java.lang.String.matches(String.java:2090)

You can add + to anything to make a possessive quantifier (it's not "doubling the quantifier"). 您可以在任何事物上加上+来构成所有格量词(不是“加倍量词”)。 So 所以

System.out.println(in.matches("\\d*+"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM