简体   繁体   English

正则表达式:所有格量词中的回溯

[英]Regular Expression: Backtracking in Possessive Quantifier

I was reviewing a test and noticed that a possessive quantifier actually worked in an str.split() . 我正在查看测试,发现所有格str.split()实际上在str.split()str.split() so I wrote the following code: 所以我写了下面的代码:

String str = "aaaaab";

if(str.matches("a*+b"))
    System.out.println("I backtrack");
else
    System.out.println("Nope.");

When run, this prints out I backtrack . 运行时,将打印出I backtrack Here's why this is confusing, I've been told that a possessive quantifier never backtracks, so why would a*+ give up the b in the String? 这就是为什么这令人困惑,有人告诉我所有格量词从不回溯,所以为什么a*+放弃String中的b

What I want is a more detailed explanation of when possessive quantifiers backtrack. 我想要的是对所有格限定词何时回溯的更详细的解释。

There is no backtracking in your example. 您的示例中没有回溯。

You are saying "any number of a characters". 你说的“任意数量的a角色”。 So, the engine will collect those 5 a chars and then stop; 因此,引擎将收集这5 a字符,然后停止; to then find the b . 然后找到b

That is all there is to this. 这就是全部。

Backtracking means that the engine has to "track back" after collecting too much of the input string; 回溯意味着引擎必须在收集到太多输入字符串之后进行“回溯”。 see here for an example of that. 看到这里的一个例子。

And beyond that: your if condition returns true when the pattern matches the input. 除此之外:当模式与输入匹配时,您的if条件返回true Your conclusion that this means "it is backtracking" is not correct: 您认为这意味着“正在回溯”的结论不正确:

A match is a match; 火柴就是火柴; no matter if the engine had to backtrack in order to match (or not). 无论引擎是否必须回溯以匹配(或不匹配)。 In other words: your little test there doesn't tell you anything (it only tells you if the input matched the given pattern; period). 换句话说:您的小测试不会告诉您任何信息(它只会告诉您输入是否匹配给定的模式;句号)。

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

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