需要全局匹配帮助的JavaScript正则表达式 [英] JavaScript regular expression with global match help needed

查看:84
本文介绍了需要全局匹配帮助的JavaScript正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JavaScript的新手,对正则表达式有疑问。我有以下代码:

I'm new to JavaScript and have a question about regular expressions. I have the following code:

var patt3=new RegExp(/(July|August)\s+\d{1,2}(\s|,)\d{4}/g);
var str3 = "August                               12,1988";
var match3 = str3.match(patt3);
document.write(match3.toString() + "<br/>");

输出结果为:1988年8月12日

The output is: August 12,1988

这是相同的代码,但是从RegExp的末尾删除了'g':

Here is the same code but with the 'g' removed from the end of the RegExp:

var patt3=new RegExp(/(July|August)\s+\d{1,2}(\s|,)\d{4}/);
var str3 = "August                               12,1988";
var match3 = str3.match(patt3);
document.write(match3.toString() + "<br/>");

输出变为:1988年8月12日,8月,

The output becomes: August 12,1988,August,,

根据我在网上找到的定义,'g'应该匹配所有出现的模式。但我仍然对'g'对代码的影响感到困惑。

From the definitions that I've found on the web, 'g' is supposed to match all occurrences of the patterns. But I'm still kind of confused as to what effect 'g' has on the code.

我非常感谢任何澄清。

提前致谢。

推荐答案

关键的区别在于字符串。匹配方法已定义以使其具有不同的行为正则表达式模式是全局的还是不是。

The crucial difference is that the string.match method is defined to have a different behavior if the regex patter is global or not.

如果模式是全局的,则是包含所有匹配项的数组。在你的情况下,你只有一个匹配,但你可以看到与例如

If the pattern is global, an array with all the matches. In your case you there is only one match but you can see the difference with an example like

let matches = "aaaa".match(/a(a)/g); 
console.log(matches) // returns ["aa", "aa"]

但是,如果模式不是全局模式,则该方法返回与找到的第一个匹配项对应的数组。该数组包含第一个位置的完整匹配字符串和其他位置的捕获。捕获是由括号分隔的正则表达式的位。同样,您可以看到与该示例的区别:

If the pattern is not global, however, the method return an array corresponding to the first match found. The array contains the full matched string in the first position and the captures in the other positions. The captures are the bits of the regex delimited by parenthesis. Again, you can see the difference with that example:

"aaaa".match(/a(a)/g); // returns ["aa", "a"]






最后,我想指出一些与您的代码有关的小问题。


Finally, I would just like to point out some minor issues with your code.

首先,您不需要使用新的Regexp 构造函数。只需直接使用正则表达式文字

First of all, you don't need to use the new Regexp constructor here. Just use the regex literal directly

var patt3 = /(July|August)\s+\d{1,2}(\s|,)\d{4}/g

其次,不要盲目toString的东西。在您的情况下,您将该方法应用于数组,这就是您得到奇怪结果的原因。

Secondly, don't blindly "toString" things. In your case you are applying that method to an array and that's why you get your weird results.

最后,学习使用开发人员工具,包括调试器和控制台。登录。它比在表现力和工作效率方面滥用document.write和alert更好。

Finally, learn to use the developer tools, including the debugger and console.log. Its much better than abusing document.write and alert in terms of expressiveness and productivity.

console.write(match3)

这篇关于需要全局匹配帮助的JavaScript正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆