这段代码:
[code="ruby"]
a="The moon is made of cheese"
show_regexp(a, /\s.*\s/)
[/code]
运行结果是:The<< moon is made of >>cheese 我看这章很迷.*不是匹配任意多个字符那应该直接到字符串尾了啊,为什么实际结果还会再匹配.*后的\s呢。
因为这种正则表达式使用贪婪匹配策略
首先看整个字符串是否匹配,如果没有发现匹配,
它去掉字符串的最后一个字符并进行再次尝试。
如果还没有发现匹配,那么在去掉最后一个字符。
所以先看" moon is made of cheese" 是否匹配/\s.*\s/
发现不行则去掉最后的e,用" moon is made of chees",再试
当用" moon is made of "进行匹配的时候,发现正确就返回结果了
/\s[^\s]\s/