【问题标题】:Javascript Regular Expression MatchJavascript 正则表达式匹配
【发布时间】:2011-11-29 19:22:29
【问题描述】:

试试

<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。 此代码应返回大小为 3 的数组,但它返回大小为 1 的数组。
问题出在哪里?

【问题讨论】:

    标签: javascript regex match


    【解决方案1】:

    您的正则表达式的.* 部分“贪婪”并尽可能多地使用字符,在这种情况下,将整个字符串作为单个匹配项返回。

    改为这样写,尾随?

    str.match(/>.*?people/img)
    

    参见描述“?”的部分在Mozilla Developer Network JS Reference

    【讨论】:

      猜你喜欢
      • 2012-09-22
      • 1970-01-01
      • 1970-01-01
      • 2011-02-19
      • 2017-03-04
      • 2015-11-13
      相关资源
      最近更新 更多