我正在使用此否定的前瞻搜索单个行字符串:
/\s+(?![^[]*]).+/g
这符合以下两个条件:
// String 1
a.casd-234[test='asfd asdf'] abc defg
// String 2
asf.one.two.three four five six
这将返回
abc defg
和four five six
我尝试编写快递以获取文本(
a.casd-234[test='asfd asdf']
,asf.one.two.three
)之前的值:/.+(?<=[^[]*])\s/g
这适用于字符串一,但不适用于字符串二,因为它找不到任何东西,因为字符串中没有
[
和]
字符。使用此后退,我在做什么错?
最佳答案
您正在使用正则表达式从某个点到其末尾匹配字符串(正则表达式末尾的.+
这样做,匹配除换行符外的1+个字符,直至行/字符串末尾)。
因此,最简单的解决方案是通过.replace
方法使用相同的模式:
var rx = /\s+(?![^[]*]).+/;
console.log("a.casd-234[test='asfd asdf'] abc defg".replace(rx, ''));
console.log("asf.one.two.three four five six".replace(rx, ''));
请注意,这里不需要
g
修饰符,因为您只需要替换一次即可。如果字符串可能有多行,请用.
或[^]
替换每个[\s\S]
。