我有一个看起来像这样的正则表达式:[@|#](.*?)\s我基本上想要的是,将匹配的正则表达式拆分为数组。所以我使用以下代码:var testString = "Hi this is a test @info@test.com and @martin we have to go."
console.log(testString.split(/(\@|\#)(.*?)\s/));我得到的结果是这样的:["Hi this is a test ", "@", "info@test.com", "and ", "@", "martin", "we have to go."]我真正想要的是:["Hi this is a test ", "@info@test.com", "and ", "@martin", "we have to go."]https://regex101.com/r/yJf9gU/1https://jsfiddle.net/xy4bgtmn/
2 回答
慕少森
TA贡献2019条经验 获得超9个赞
不要使用split,使用match:
testString.match(/[@#]\S+|[^@#]+/g)
// ["Hi this is a test ", "@info@test.com", " and ", "@martin", " we have to go."]
@此正则表达式仅匹配 an或 a之后的所有非空格#,或者匹配所有非@或#字符,有效地将其分成块。
慕哥9229398
TA贡献1877条经验 获得超6个赞
[#@]您可以通过放置在捕获组内然后匹配 1+ 个非空白字符来 使用 split([#@]\S+)
let s = "Hi this is a test @info@test.com and @martin we have to go.";
console.log(s.split(/([#@]\S+)/));
添加回答
举报
0/150
提交
取消