简体   繁体   English

RegExp对象保留先前的匹配项

[英]RegExp object holding on to prior matches

Consider this Javascript regular expression code: 考虑以下Javascript正则表达式代码:

v = 'The dog jumped over the moon';

// Matches
if (v.match(/(jump)ed/)) {
    alert('Initial: ' + RegExp.$1); // Alerts "jump"
}

// Obviously not matched, but RegExp object retains previous match
if (v.match(/(gygyujgujy)/)) {
    alert(RegExp.$1);
}

// Alerts "jump" but shouldn't this be null/false etc?
alert('Final: ' + RegExp.$1);

The second regular expression, despite not matching, holds on to the first regular expressions matches. 第二个正则表达式尽管不匹配,但仍保留第一个正则表达式匹配。

Shouldn't the RegExp object be empty because of the no match on the second regular expression? 由于第二个正则表达式不匹配,RegExp对象是否不应为空?

from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/n 来自https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp/n

"The $1, ..., $9 properties are static, they are not a property of an individual regular expression object. Instead, you always use them as RegExp.$1, ..., RegExp.$9. “ $ 1,...,$ 9属性是静态的,它们不是单个正则表达式对象的属性。相反,您始终将它们用作RegExp。$ 1,...,RegExp。$ 9。

The values of these properties are read-only and modified whenever successful matches are made." 这些属性的值是只读的,只要成功匹配就可以修改。”

Since your 2nd if-statement never matches anything, no new value will be assigned to $1 由于您的第二个if语句从不匹配任何内容,因此不会将新值分配给$ 1

They are non-standard properties and documented as: 它们是非标准属性,并记录为:

The values of these properties are read-only and modified whenever successful matches are made. 这些属性的值是只读的,并且每当成功匹配时都将对其进行修改。

There is no match for gygyujgujy so the existing value remains. gygyujgujy没有匹配项,因此保留了现有值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM