javascript - 如何制作仅捕获一个符号但有限制的正则表达式?

标签 javascript regex

我需要一个 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/

相关文章:

javascript - 从抓取的 Javascript 表列表创建 DataFrame

javascript - => 在 JavaScript 中是什么意思? (等于大于)

javascript - Angular : Directive with watch in link

regex - Grep 查找以特定字符结尾的字符串

python - 如何从正则表达式匹配中获取索引?

regex - Rob Pikes 正则表达式的惯用 Rust 重写

python - 正则表达式替换中的匹配数

javascript - d3 路径 d = MNaN,NaNLNaN,NaN

javascript - 在事件上运行 javascript 文件

javascript - 在同一页面正则表达式中获取哈希链接