正则表达式:星重复运算符的所有格量词,即\ d ** [英] Regex: possessive quantifier for the star repetition operator, i.e. \d**

查看:182
本文介绍了正则表达式:星重复运算符的所有格量词,即\ d **的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

摘自《 GLib参考手册》的常规表达式语法" ,小节原子分组和所有格":

From the GLib Reference Manual, section "Regular expression syntax", subsection "Atomic grouping and possessive quantifiers":

在将模式\d+foo应用于字符串123456bar时,请考虑以下模式:匹配所有6位数字,然后不匹配"foo",匹配器的正常动作是仅使用5位数字与\匹配来重试. d +项目,然后加上4,依此类推,直到最终失败.

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(称为 atomic grouping ),则匹配器在无法匹配"foo"或"foo"时会立即放弃.第一次.

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

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

我的问题是:是否有任何理由说明恒星(*)重复运算符没有等效项?

My question is: is there any reason why there is no equivalent for the star (*) repetition operator?

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

异常堆栈跟踪为:

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*+"));

这篇关于正则表达式:星重复运算符的所有格量词,即\ d **的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆