[英]Why does my regex in JavaScript return undefined?
我正在尝试在字符串中查找所有与“ test”匹配的内容:
const search = "test"; const regexString = "(?:[^ ]+ ){0,3}" + "test" + "(?: [^ ]+){0,3}"; const re = new RegExp(regexString, "gi"); const matches = []; const fullText = "my test string with a lot of tests that should match the test regex"; let match = re.exec(fullText); while (match != undefined) { matches.push(match[1]); match = re.exec(fullText); } console.log(matches);
我得到以下内容:
[ undefined, undefined, undefined ]
为什么我的搜索不起作用?
您的代码期望匹配的结果包括在正则表达式的捕获组中捕获的内容。 但是,您的正则表达式仅包含非捕获组。 在(?: )
分组明确不捕获匹配的子字符串。
您需要简单的( )
分组。
由于要调用捕获组( match[1]
),因此应将非捕获组(?:...)
在捕获组(...)
)中。 :
"((?:\\S+ ){0,3})" + search + "((?: \\S+){0,3})"
尝试返回包含“ test”之前和进行中的3个单词的数组
然后,您需要将两个捕获的组推入一个组:
matches.push([match[1], search, match[2]]);
// `match[1]` refers to first capturing group
// `match[2]` refers to second CG
// `search` contains search word
JS代码:
const search = "test"; const regexString = "((?:\\\\S+ ){0,3})" + search + "((?: \\\\S+){0,3})"; const re = new RegExp(regexString, "gi"); const matches = []; const fullText = "my test string with a lot of tests that should match the test regex"; while ((match = re.exec(fullText)) != null) { matches.push([match[1], search, match[2]]); } console.log(matches);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.