我发现这个关于正则表达式的优秀教程,虽然我直观地理解"贪婪","不情愿"和"占有欲"量词的作用,但我的理解似乎存在严重漏洞.
具体来说,在以下示例中:
Enter your regex: .*foo // greedy quantifier
Enter input string to search: xfooxxxxxxfoo
I found the text "xfooxxxxxxfoo" starting at index 0 and ending at index 13.
Enter your regex: .*?foo // reluctant quantifier
Enter input string to search: xfooxxxxxxfoo
I found the text "xfoo" starting at index 0 and ending at index 4.
I found the text "xxxxxxfoo" starting at index 4 and ending at index 13.
Enter your regex: .*+foo // possessive quantifier
Enter …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用正则表达式将字符串分成两部分.字符串格式如下:
text to extract<number>
Run Code Online (Sandbox Code Playgroud)
我一直在使用(.*?)<,<(.*?)>哪个工作正常,但在阅读了一点regex之后,我才开始想知道为什么我需要?表达式中的.我通过这个网站找到它们之后才这样做,所以我不确定它们之间的区别.
我有一个非常简单的正则表达式与此类似:
HOHO.*?_HO_
有了这个测试字符串...
fiwgu_HOHO_HOHO_HOHOrgh_HOHO_feh_HOHO___HO_fbguyev
_HOHO___HO_(最短匹配,非贪婪)_HOHO_HOHO_HOHOrgh_HOHO_feh_HOHO___HO_(最长的匹配,看起来很贪婪)。为什么?如何使它匹配最短的匹配项?
添加和删除的?结果相同。
编辑 -更好的测试字符串,显示为什么[^HOHO]不起作用:fiwgu_HOHO_HOHO_HOHOrgh_HOHO_feh_HOHO_H_O_H_O_HO_fbguye
我能想到的是,它可能多次匹配-但只有一个匹配_HO_,所以我不明白为什么它没有采用以结尾的最短匹配_HO_,而丢弃了其余匹配。
我已经浏览了所有标题为“非贪婪正则表达式贪婪”之类的问题,但它们似乎都存在其他问题。