简体   繁体   中英

RegExp matching @ mention tags with optional space

I'm working with some code that uses the regex /(@\w+) ?/g for matching tagged mentions

This will match the following text returning the groups correctly without the additional space

testing @one and @two and @three

If I remove the optional space ? the regex /(@\w+)/g appears to return the same matching groups - for the above example and any other test strings I've tried

Is there some subtle difference or edge case that I might be missing between these two version of the regex?

If there is a space the regex will match it, but it won't affect the matching groups because the space isn't in any group. Only the whole match will have the space.

console.log(...'testing @one and @two and @three'.matchAll(/(@\w+) ?/g));
// [ "@one ", "@one" ]
// [ "@two ", "@two" ]
// [ "@three", "@three" ]

The first element of each result array is the whole match and the second element is what is matched by the group (@\w+) .

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