首页 > 解决方案 > 为什么这两个 JavaScript 正则表达式会产生不同的结果?

问题描述

首先,我有:

const regEx = /(?:\S+\s)?\S*text\S*(?:\s\S+)?/;
const fullText = "one two text three four";
console.log(fullText.match(regEx));

这导致

['二文字三',索引:4,输入:'一二文字三四']

然后我有:

const regEx2 = new RegExp("(?:\S+\s)?\S*text\S*(?:\s\S+)?", "g");
const fullText2 = "one two text three four";
console.log(fullText2.match(regEx2));

这导致:

[ '文本' ]

使用new RegExp,如何获得与第一个代码块相同的结果?

标签: javascriptregex

解决方案


推荐阅读