Heim  >  Artikel  >  Backend-Entwicklung  >  Java、正则:为什么这两个匹配的意思相同呢?

Java、正则:为什么这两个匹配的意思相同呢?

WBOY
WBOYOriginal
2016-06-06 20:36:541014Durchsuche

<code>java</code><code>Pattern p = Pattern.compile("(?=hopeful)hope");  
String str = "hopeful";  
Matcher m = p.matcher(str);  
while(m.find()){  
   System.out.println(m.group());  
}
</code>

是否能匹配hopeful,如果能,则捕获hopeful中的hope。

当然继续向后查找匹配的子串,是从f开始。比较一下可以看出,(?=hopeful)hope和hope(?=ful),两个正则的效果其实是一样的

虽然看到了上面的说明还是不能理解,只见过hope(?=ful)这种写法,另一种写法该怎么理解呢?我一直以为(?=)就是用来匹配是否以xxx结尾这种形式的...

回复内容:

<code>java</code><code>Pattern p = Pattern.compile("(?=hopeful)hope");  
String str = "hopeful";  
Matcher m = p.matcher(str);  
while(m.find()){  
   System.out.println(m.group());  
}
</code>

是否能匹配hopeful,如果能,则捕获hopeful中的hope。

当然继续向后查找匹配的子串,是从f开始。比较一下可以看出,(?=hopeful)hope和hope(?=ful),两个正则的效果其实是一样的

虽然看到了上面的说明还是不能理解,只见过hope(?=ful)这种写法,另一种写法该怎么理解呢?我一直以为(?=)就是用来匹配是否以xxx结尾这种形式的...

(?=exp) 匹配exp前面的位置

(?=hopeful)hope -> (?=hopeful) + hope

(?=hopeful)定位是hopeful中h的index 向后匹配的话 就找到了hope

hope(?=ful) -> hope + (?=ful)

先找到hope 之后匹配ful的index 可以试试hope(?=ful)ful去匹配hopeful

你可以假想匹配是在文本编辑器里把光标挪到匹配文本的开始位置,并选中捕获文字。
hope 匹配效果是 |hope... 竖线表示光标位置,下一个匹配从e之后开始。
(?ful) 匹配ful,但是捕获长度为0,效果相当于 ...|ful
两者结合就是匹配整个hopeful但是只捕获hope

(?hopeful) 匹配效果为 |hopeful, 匹配了整个hopeful,并且下个匹配仍从h开始
后续 hope 匹配效果是 |hope...
效果与上面的正则式相同。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn