Javascript 为什么这个正则表达式也匹配非捕获组中的单词?
我有这个字符串(注意多行语法):Javascript 为什么这个正则表达式也匹配非捕获组中的单词?,javascript,regex,Javascript,Regex,我有这个字符串(注意多行语法): var str = ` Number One: Get this Number Two: And this`; [str, 'Get this', 'And this'] ["Number One: Get this", "Number Two: And this"] 我想要一个返回的正则表达式(与匹配): var str = ` Number One: Get this Number Two: And this`; [str,
var str = ` Number One: Get this
Number Two: And this`;
[str, 'Get this', 'And this']
["Number One: Get this", "Number Two: And this"]
我想要一个返回的正则表达式(与匹配):
var str = ` Number One: Get this
Number Two: And this`;
[str, 'Get this', 'And this']
["Number One: Get this", "Number Two: And this"]
所以我尝试了str.match(/Number(?:One | Two):(.*)/g)代码>,但返回:
var str = ` Number One: Get this
Number Two: And this`;
[str, 'Get this', 'And this']
["Number One: Get this", "Number Two: And this"]
在任何“Number”
单词之前可以有任何空格/换行符
为什么它不只返回捕获组内部的内容?我是不是误解了什么?我怎样才能达到预期的效果呢?Per:
如果正则表达式包含g
标志,则该方法将返回一个包含所有匹配子字符串而不是匹配对象的字符串不返回捕获的组。如果没有匹配项,则方法返回
(我的重点)
所以,你想要的是不可能的
同一页增加了:
- 如果要获取捕获组并且设置了全局标志,则需要使用
因此,如果您愿意使用match
,您可以编写自己的函数,重复应用正则表达式,获取捕获的子字符串,并构建一个数组
或者,针对您的具体情况,您可以写以下内容:
var these = str.split(/(?:^|\n)\s*Number (?:One|Two): /);
these[0] = str;
试一试
var str=“第一:得到这个\
第二:这个”;
//`/\w+\s+\w+(?=\s |$)/g`匹配一个或多个字母数字字符,
//后跟一个或多个空格字符,
//后跟一个或多个字母数字字符,
//如果在输入的空格或结尾之后,请设置“g”标志
//return`res`array`[“获取这个”,“和这个”]`
var res=str.match(/\w+\s+\w+(?=\s |$)/g);
document.write(JSON.stringify(res))代码>将结果替换并存储在新字符串中,如下所示:
var str = ` Number One: Get this
Number Two: And this`;
var output = str.replace(/Number (?:One|Two): (.*)/g, "$1");
console.log(output);
哪些产出:
Get this
And this
如果您希望获得所需的匹配数组,可以尝试以下操作:
var getMatch = function(string, split, regex) {
var match = string.replace(regex, "$1" + split);
match = match.split(split);
match = match.reverse();
match.push(string);
match = match.reverse();
match.pop();
return match;
}
var str = ` Number One: Get this
Number Two: And this`;
var regex = /Number (?:One|Two): (.*)/g;
var match = getMatch(str, "#!SPLIT!#", regex);
console.log(match);
将根据需要显示阵列:
[ ' Number One: Get this\n Number Two: And this',
' Get this',
'\n And this' ]
Where split(此处#!split!#
)应该是分割匹配项的唯一字符串。请注意,这仅适用于单个组。对于多组,添加一个表示组数的变量,并添加一个For循环构造“$1$2$3$4…”+split
好的,谢谢。你知道所有的正则表达式引擎都是一样的吗?我的意思是,如果这是因为正则表达式通常的工作方式。我想我正在这样做(当然,声明arr
):str.split('\n')。forEach(x=>arr.push(x.match(/Number(?:一|二):(.*)/[1])代码>,你觉得怎么样?啊,没有看到更新,也可以。@guest271314的解决方案也很有效,但您解释了为什么没有,这很好。谢谢我不是真的对整个字符串感兴趣,我只是在问题中这样写的,因为这就是我认为match总是与捕获组一起工作的方式。谢谢。这也很好,而且使用箭头功能更棒!:var res=str.match(/:\s+\w+\s+\w+/g).map(v=>v.replace(“:”,”)代码>谢谢!整个字符串对我来说并不那么重要,我只是指出了它,因为我认为匹配的工作方式。在第一个示例中,还可以执行以下操作:output.trim().split('\n')代码>获取数组,我猜。是的,这在这种情况下也会起作用,但我认为如果有一行没有匹配项,它将失败。啊,是的,你是对的,它还将包括数组中的非匹配项。