簡體   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