JavaScript正则表达式匹配
问题描述:
<script type="text/javascript">
var str=">1 people>9 people>1u people";
document.write(str.match(/>.*people/img).length);
</script>
在http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_regexp_dot。 此代码应该返回一个大小为的数组,但它会返回大小为的数组。
问题在哪里?
答
.*
.*
你的正则表达式的一部分正在“贪婪”,并尽可能多地取得字符,在这种情况下,将整个字符串作为单个匹配返回。
写这样的替代,具有尾随?
:
str.match(/>.*?people/img)
请参阅部分描述 “?”在Mozilla Developer Network JS Reference。