我需要一个 javascript 的正则表达式,它允许我选择一个有限制的字符:除了它自己之外没有指定的字符。
我需要选择字符/
但前提是它旁边没有字符 a
。
例如:
str = "I Like this/ and a/ basketball is round a/a ups.Papa/ tol/d /me tha/t";
myregex = ????
var patt = new RegExp(myregex);
var res = patt.split(str);
结果应该是这样的:
res[0] = "I Like this"
res[1] = " and a/ basketball is round a/a ups.Papa/ tol"
res[2] = "d "
res[3] = "me tha/t"
正则表达式应该是这样的:
(如果a则不)(\/)(如果a则不)
我不知道该怎么做,我试过:[^a](\/)[^a]
,但它也选择了 /旁边的字符
,像s/
,l/d
,不是a
;我不想选择 /
旁边的字符。
最佳答案
由 /(?<!a)\//g
拆分
var output = "I Like this/ and a/ basketball is round a/a ups.Papa/ tol/d /me tha/t".split(/(?<!a)\//g);
console.log(output);
解释
-
/(?<!a)\/
火柴/
前面没有a
注意
- 适用于 chrome,不适用于 FF,正如@SoulReaver 在他的评论中所建议的那样。
编辑
或者,您可以按 /
拆分
var output = "I Like this/ and a/ basketball is round a/a ups.Papa/ tol/d /me tha/t".split(/\//g);
output = output.reduce( function(a,c){
var lastItem = a.slice(-1)[0];
//console.log(lastItem)
if ( lastItem && lastItem.slice(-1) == "a" )
{
a.pop();
a.push(lastItem.concat("/").concat(c));
}
else
{
a.push(c);
}
return a;
}, [])
console.log(output);
编辑2
如果a
必须忽略 /
的两边,然后使用之前的答案(基于 reduce),只需在 split
中添加 look-ahead
var output = "I Like this/ and a/ basketball is round a/a ups.Papa/ tol/d /me tha/t".split(/\/(?!=a)/g);
关于javascript - 如何制作仅捕获一个符号但有限制的正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48320414/