亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

正則表達式只得到完全匹配(不分組)

正則表達式只得到完全匹配(不分組)

嚕嚕噠 2023-06-15 09:28:21
我有一個看起來像這樣的正則表達式:[@|#](.*?)\s我基本上想要的是,將匹配的正則表達式拆分為數組。所以我使用以下代碼:var testString = "Hi this is a test @[email protected] and @martin we have to go." console.log(testString.split(/(\@|\#)(.*?)\s/));我得到的結果是這樣的:["Hi this is a test ", "@", "[email protected]", "and ", "@", "martin", "we have to go."]我真正想要的是:["Hi this is a test ", "@[email protected]", "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 ", "@[email protected]", " and ", "@martin", " we have to go."]

@此正則表達式僅匹配 an或 a之后的所有非空格#,或者匹配所有非@或#字符,有效地將其分成塊。


查看完整回答
反對 回復 2023-06-15
?
慕哥9229398

TA貢獻1877條經驗 獲得超6個贊

[#@]您可以通過放置在捕獲組內然后匹配 1+ 個非空白字符來 使用 split([#@]\S+)


let s = "Hi this is a test @[email protected] and @martin we have to go.";

console.log(s.split(/([#@]\S+)/));


查看完整回答
反對 回復 2023-06-15
  • 2 回答
  • 0 關注
  • 159 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號