[英]How to split a string on the first occurrence of one of multiple substrings in JavaScript?
給定字符串
s1 = "abcfoodefbarghi"
和
s2 = "abcbardefooghi"
如何將s1拆分為“abc”和“defbarghi”,將s2拆分為“abc”和“defooghi”即:在第一次出現字符串“foo”或“bar”時將字符串拆分為兩個
我想這可以用s.split(/regexp/)
,但這個正則表達式應該是什么?
以這種方式使用正則表達式:
var match = s1.match(/^([\S\s]*?)(?:foo|bar)([\S\s]*)$/);
/* If foo or bar is found:
match[1] contains the first part
match[2] contains the second part */
RE的解釋:
[\\S\\s]*?
匹配足夠的字符以匹配RE的下一部分,即 (foo|bar)
“foo”或“bar” [\\S\\s]*
匹配剩余的字符 RE的一部分周圍的括號創建一個組,以便可以引用分組的匹配,而(?:)
創建一個不可引用的組。
str.replace(/foo|bar/,"\x034").split("\x034")
idea是用特殊的(不可見的)String替換第一個匹配項,然后對該字符串進行拆分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.