正则匹配以'iphone~'开头文本的结果异常问题求助
正则匹配问题:匹配以“iphone~”开头的文本返回结果异常
问题场景
匹配以#开头的标签时,代码运行正常:
const matchHashtags = /(#\w+) ?/g; const text ="this is #sample tag and other #another tag"; while ((hashtag = matchHashtags.exec(text))) { alert(hashtag); }
但匹配以iphone~开头的文本时,结果不符合预期:
const matchHashtags2 = /(^|\s)\iphone~(\w+)/g; const text2 ="I have iphone~seven~new and iphone~seven~ old phones"; while ((hashtag2 = matchHashtags2.exec(text2))) { alert(hashtag2); }
预期匹配到iphone~seven,实际返回数组包含三个值:"iphone~seven", "", "seven"。
问题原因
exec方法返回的数组中,第一个元素是完整匹配结果,后续元素对应正则表达式里的捕获组内容。你的正则里写了(^|\s)和(\w+)两个捕获组,所以返回数组会包含这两个组的匹配值。
解决方法
方法1:使用非捕获组+指定捕获目标
把不需要保留的分组改为非捕获组((?:...)),只捕获目标内容:
const matchHashtags2 = /(?:^|\s)(iphone~\w+)/g; const text2 ="I have iphone~seven~new and iphone~seven~ old phones"; let hashtag2; while ((hashtag2 = matchHashtags2.exec(text2))) { alert(hashtag2[1]); // 取目标捕获组的内容 }
方法2:直接匹配目标内容
简化正则,直接匹配iphone~后跟单词字符的部分,通过exec返回数组的第一个元素获取结果:
const matchHashtags2 = /iphone~\w+/g; const text2 ="I have iphone~seven~new and iphone~seven~ old phones"; let hashtag2; while ((hashtag2 = matchHashtags2.exec(text2))) { alert(hashtag2[0]); // 取完整匹配结果 }
两种方法都能得到预期的iphone~seven结果。
内容的提问来源于stack exchange,提问作者Billy
相关产品推荐
相关产品推荐

