简体   繁体   中英

Why does my regex in JavaScript return undefined?

I'm trying to find all the matches for 'test' in my string:

 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); 

I'm getting the following:

[ undefined, undefined, undefined ]

Why isn't my search working?

Your code expects the result of the match to include stuff captured in capturing groups in the regular expression. However, your regular expression contains only non-capturing groups. The (?: ) grouping explicitly does not capture the matched substring.

You want plain ( ) groupings.

You should enclose your non-capturing groups (?:...) in a capturing group (...) since you are invoking a capturing group ( match[1] ). :

"((?:\\S+ ){0,3})" + search + "((?: \\S+){0,3})"

Trying to return an array containing the 3 words preceding and proceeding 'test'

Then you need to push both captured groups not one:

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 code:

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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