关于regular expression中的
(?=re) 我的理解就是“匹配,但不包含在结果内” (Matches re at this point, but does not consume it)。
从"Programming Ruby - The Pragmatic Programmer's Guide"摘的例子:
str
=
"
red, white, and blue
"
1 ) str.scan(/[a-z]+,/) 结果: ["red," "white,"]
2) str
.
scan(
/
[a-z]
+
(?=,)
/
)
结果:
[
"
red
"
,
"
white
"
]
逗号没有包含在2)的 匹配的 结果内
另外一个我简化过的例子:
原例子见: http://rubyforge.org/snippet/detail.php?type=snippet&id=8
从"Programming Ruby - The Pragmatic Programmer's Guide"摘的例子:
![](https://i-blog.csdnimg.cn/blog_migrate/6810355c2f78c12e91b7997a8e8c583a.gif)
1 ) str.scan(/[a-z]+,/) 结果: ["red," "white,"]
![](https://i-blog.csdnimg.cn/blog_migrate/6810355c2f78c12e91b7997a8e8c583a.gif)
逗号没有包含在2)的 匹配的 结果内
另外一个我简化过的例子:
1) "
-123456789
"
.gsub(
/
(/d)(/d{3}+$)/,'/1,/2')
结果:"-123,456789"
2) " -123456789 " .gsub( / (/d)( ?=/d {3} +$) / , ‘/1,' ) 结果: " -123,456,789 "
因为 /d {3} +$ 没有包含在匹配的结果内+gsub,产生递归的效果。而1)则没有
2) " -123456789 " .gsub( / (/d)( ?=/d {3} +$) / , ‘/1,' ) 结果: " -123,456,789 "
因为 /d {3} +$ 没有包含在匹配的结果内+gsub,产生递归的效果。而1)则没有
原例子见: http://rubyforge.org/snippet/detail.php?type=snippet&id=8