我很确定我在这里遗漏了一些明显的东西,但我不能让 R 使用非贪婪的正则表达式:
> library(stringr)
> str_match('xxx aaaab yyy', "a.*?b")
[,1]
[1,] "aaaab"
基本函数的行为方式相同:
> regexpr('a.*?b', 'xxx aaaab yyy')
[1] 5
attr(,"match.length")
[1] 5
attr(,"useBytes")
[1] TRUE
我希望匹配只是
ab
根据 http://stat.ethz.ch/R-manual/R-devel/library/base/html/regex.html 中的“贪婪”评论:By default repetition is greedy, so the maximal possible number of repeats is used. This can be changed to ‘minimal’ by appending ? to the quantifier. (There are further quantifiers that allow approximate matching: see the TRE documentation.)
有人可以解释一下这是怎么回事吗?
更新。 疯狂的是,在其他一些情况下,非贪婪模式的行为符合预期:
> str_match('xxx <a href="abc">link</a> yyy <h1>Header</h1>', '<a.*>')
[,1]
[1,] "<a href=\"abc\">link</a> yyy <h1>Header</h1>"
> str_match('xxx <a href="abc">link</a> yyy <h1>Header</h1>', '<a.*?>')
[,1]
[1,] "<a href=\"abc\">"
最佳答案
困难的概念,所以我会尽我所能......如果它有点令人困惑,有人可以随意编辑和解释得更好。
从左到右搜索与您的模式匹配的表达式。是的,以下所有字符串 aaaab
, aaab
, aab
, 和 ab
与您的模式匹配,但 aaaab
从最左边开始的那个是返回的那个。
所以在这里,你的非贪婪模式不是很有用。当非贪婪模式出现时,也许这个另一个例子会帮助你更好地理解:
str_match('xxx aaaab yyy', "a.*?y")
# [,1]
# [1,] "aaaab y"
这里所有的字符串
aaaab y
, aaaab yy
, aaaab yyy
匹配模式并从相同位置开始,但由于非贪婪模式,第一个被返回。那么你能做些什么来捕捉最后一个
ab
?用这个:str_match('xxx aaaab yyy', ".*(a.*b)")
# [,1] [,2]
# [1,] "xxx aaaab" "ab"
它是如何工作的?通过添加贪婪模式
.*
在前面,您现在正在强制进程放置最后一个可能的 a
进入捕获组。
关于regex - 非贪婪字符串正则表达式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16577432/