簡體   English   中英

Javascript RegExp-它包含空格和方括號

[英]Javascript RegExp - it include space and brackets around

正則表達式的菜鳥

請檢查我的嘗試

我想將方括號內沒有連字符或其他字符的數字分隔開-然后在這些數字周圍加上引號

到目前為止,我有- [^az-0-9](\\d+)[^0-9-az]

匹配的數字組-不能以數字或字符開頭或結尾

當前匹配(1,2)而不是1和2

測試

(0-hyphen-number) OR
(123 no hyphen) OR
(no hyphen 2) OR
(no 3 hyphen) OR
(no -4- hyphen) OR
(no -5 hyphen) OR
(no 6- hyphen) OR
(blah 0987 hyp1hen) OR
(blah -4321 hyp-2hen) OR
(blah -1234- hyp3-hen)

預期輸出:)

(0-hyphen-number) OR
("123" no hyphen) OR
(no hyphen "2") OR
(no "3" hyphen) OR
(no -4- hycphen) OR
(no -5 hyphden) OR
(no 6- hyphen) OR
(blah "0987" hyp1hen) OR
(blah -4321 hyp-2hen) OR
(blah -1234- hyp3-hen)

您的正則表達式足夠接近。 但是,您應該-在結尾或開頭或字符類上輸入。

您應該捕獲所有組並按如下所示替換它們。

正則表達式: ([^a-z0-9-])(\\d+)([^0-9a-z-])

替換為:替換為$1"$2"$3

Regex101演示

do not have hyphen or other characters around them apart from brackets

您應注意,原始正則表達式[^az-0-9](\\d+)[^0-9-az]
匹配數字附近的任何標點符號。

因此,, ,888+,888]*888}將匹配。

但是您可能正在尋找的是這樣的東西

(?:^|[\\s()])(\\d+)(?:[\\s()]|$)

僅允許空白邊界或父級邊界。

[\\s()]更改為[\\s(][\\s}]以適應您的需求。


修改:還要獲取空格分隔的數字。
https://regex101.com/r/pO4mO1/3

(?:^|[\\s()])(\\d+(?:\\s*\\d)*)(?:[\\s()]|$)

展開式

 (?:
      ^ 
   |  [\s()] 
 )
 (                             # (1 start)
      \d+ 
      (?: \s* \d )*
 )                             # (1 end)
 (?:
      [\s()] 
   |  $ 
 )

到我加載Regex101時,它已經具有此正則表達式: [^az-0-9](\\d+)[^0-9-az]

僅供參考(對於每個困惑的人),在該帖子的早期版本中,正則表達式為^az-0-9[^0-9-az] 另一個用戶編輯了帖子以反映他們在演示中看到的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM