繁体   English   中英

javascript正则表达式在匹配前检查字符,但不将其包含在结果中

[英]javascript regex check character before match but don't include it in result

我正在尝试在单个正则表达式中实现以下两个规则:

如果数字前面有:

  • 单词字符或@字符; 那什么都不配
  • 还要别的吗 ; 然后匹配数字, 结果中不包含前一个字符

我尝试过: [^@\\d,\\w]\\d+(?:[^@\\d,\\w])\\d+

哪个解决了第一个规则,但未能解决第二个规则,因为它在结果中包括了运算符。

我明白为什么它不能正常工作; [^@\\d\\w]部分明确表示与@或单词字符前面的数字不匹配,因此它隐式表示要在结果中包括其他任何内容。 问题是我仍然不知道该如何解决。

有没有办法在单个正则表达式中实现这两个规则?

输入字符串:

@121 //do not match
+39  //match but don't include the + sign in result
s21  //do not match
89   //match
(98  //match but don't include the ( in result
/4   //match but don't include the / operator in result

预期结果:

39 //operator removed
89  
98 //( removed
4  //operator removed

捕获您要寻找的结果,如下面的代码段所示。

查看正则表达式在这里使用

^[^@\w]?(\d+)
  • ^在行首处声明位置
  • [^@\\w]? (可选)匹配@或单词字符以外的任何字符
  • (\\d+)一个或多个数字捕获到捕获组1中

 var a = ["@121", "+39", "s21", "89", "(98", "/4"] var r = /^[^@\\w]?(\\d+)/ a.forEach(function(s){ var m = s.match(r) if(m != null) console.log(m[1]) }) 

一个关于否定性回溯的完整建议 ,我想这就是您要寻找的:

 let arr = ['@121', //do not match '+39', //match but don't include the + sign in result 's21', //do not match '89', //match '(98', //match but don't include the ( in result '/4' //match but don't include the / operator in result ]; console.log(arr.map(v => v.match(/(?<![@\\w])\\d+/))); 

但是,这是一个前沿功能(我认为适用于62+以上的铬)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM