我正在寻找一个正则表达式来拆分用户在:
字符上提供的字符串,但不是当用户转义冒号\:
或它是url的一部分时,例如https://stackoverflow..
。在javascript中,大多数浏览器还不支持lookbehinds。是否有可能对后视部分应用其他方法?
在Chrome上的clojure/ Clojurescript (支持lookbehinds)中,这个正则表达式做到了这一点:
#"(?<!\):(?!//)"
但不是在Safari中(例如)。
发布于 2019-06-02 15:35:50
主要的问题是,目前的浏览器不支持后视,这是查找和否定前缀\
所必需的,所以我们不包括\:
。
一种解决办法(不是很漂亮,但很有效)是首先用一些你知道不会自然出现在你的文本中的“符号”替换\:
,做你的拆分,然后替换回任何\:
。
例如,如果字符串中有"::“,此方法将返回空元素"”:
let regex = /:(?!\/\/)/
//original string literal \: has to be expressed as \\:
let str = "http://example.com::hello:dolly:12\\:00\\:PM";
//substitute out any \:
str = str.replace(/\\:/g,"<colon>"); //http://example.com::hello:dolly:12<colon>00<colon>PM
//now we split 'normally' without lookbehind
let arr = str.split(regex); //[ 'http://example.com', '', 'hello', 'dolly', '12\\:00\\:PM' ]
//substitute back \:
arr = arr.map(element => element.replace(/<colon>/g, "\\:")); //[ 'http://example.com', '', 'hello', 'dolly', '12\\:00\\:PM' ]
console.log(arr);
如果你只是在寻找非空元素,你可以在它上面做一个arr.filter(Boolean)
,或者直接使用@Skeeve的匹配解决方案,因为它在这方面更优雅。
https://stackoverflow.com/questions/56412475
复制相似问题