简体   繁体   English

正则表达式匹配带有可选空格的@提及标签

[英]RegExp matching @ mention tags with optional space

I'm working with some code that uses the regex /(@\w+) ?/g for matching tagged mentions我正在使用一些使用正则表达式/(@\w+) ?/g匹配标记提及的代码

This will match the following text returning the groups correctly without the additional space这将匹配以下文本,正确返回组,而无需额外的space

testing @one and @two and @three测试@one@two@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正则表达式/(@\w+)/g似乎返回相同的匹配组-对于上面的示例和我尝试过的任何其他测试字符串

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+) .每个结果数组的第一个元素是整个匹配项,第二个元素是组匹配的内容(@\w+)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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