【问题标题】:match() returns array with two matches when I expect one match当我期望一个匹配时,match() 返回具有两个匹配的数组
【发布时间】:2012-02-18 15:22:20
【问题描述】:

考虑以下示例:

<html>
<body>

<script type="text/javascript">

var str="filename.jpg";

var pattOne = new RegExp('\.[^\.]*$');
var pattTwo = new RegExp('(\.[^\.]*$)');
var pattThree = new RegExp('(\.[^\.]*$)', 'g');

document.write(str.match(pattOne));
document.write('<br>');
document.write(str.match(pattTwo));
document.write('<br>');
document.write(str.match(pattThree));

</script>
</body>
</html>

结果如下:

.jpg
.jpg,.jpg
.jpg

我期待这个结果:

.jpg
.jpg
.jpg

为什么在正则表达式周围加上括号会改变结果?为什么使用 'g' 修饰符会再次改变结果?

【问题讨论】:

    标签: javascript regex string match


    【解决方案1】:

    来自String.prototype.match [MDN]

    如果正则表达式不包含g 标志,则返回与regexp.exec(string) 相同的结果。

    RegExp.prototype.exec documentation [MDN] 说:

    返回的数组将匹配的文本作为第一项,然后每个匹配的捕获括号对应一个项目,其中包含捕获的文本。

    因此,当您在第二个表达式中引入捕获组时,第一个元素是整个匹配项,第二个元素包含捕获组的内容,在您的示例中,它也是整个匹配项。
    第一个表达式没有捕获组,因此您只能取回匹配项。

    返回match 文档:

    如果正则表达式包含g 标志,则该方法返回一个包含所有匹配项的数组。如果没有匹配,该方法返回null

    使用g 修饰符,只返回匹配项,而不返回捕获组的内容。在您的字符串中只有一个匹配项。

    【讨论】:

      【解决方案2】:

      .match() 函数返回一个数组。 document.write() 将数组打印为字符串。

      当你在字符串中捕获一个组时,它会生成一个这样的数组:

      Array(
        [0] => 'the complete matched string',
        [1] => 'the first captured group',
        [2] => 'the second captured group', 
        [.] => '...'
      )
      

      所以用你的正则表达式它变成:

      Array(
        [0] => '.jpg', // You match .jpg of the string
        [1] => '.jpg' // You captured the .jpg match
      )
      

      如果你打印一个数组,它会在值之间放置一个,

      【讨论】:

      • 答案是正确的,为了清楚起见:捕获小组赛是因为添加了括号。当您喜欢处理某些子匹配时,这很有帮助。例如,这是可能的:var pattOne = new RegExp('\.([^\.]*)$');,而不是组仅包含文件扩展名而没有点。
      • 我看到一些 PHP 在那里戳穿
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多