簡體   English   中英

RegEx用於將字母數字模式與量詞匹配

[英]RegEx for matching an alphanumeric pattern with quantifier

我正在嘗試將正則表達式中的數字限制在4到6之間,但是它不起作用

最小范圍有效,但最大范圍無效:

  • Some Text-1 =驗證
  • Some Text-201901 =驗證
  • Some Text-20190101 =在失敗的地方通過了驗證

現在,如果我在末尾添加$,則上述所有操作均無效。

碼:

^[A-Z ]{3,}-\d{4,6}

你想用

^[A-Z ]{3,}-[0-9]{3,6}(?!\d)

細節

  • ^ -字符串的開頭
  • [AZ ]{3,} -三個或更多大寫字母或空格
  • -連字符
  • [0-9]{3,6} -三到六位數
  • (?!\\d) -如果在當前位置的右邊立即有一個數字,則匹配將使匹配失敗。

我不太確定,我們可能希望通過和失敗,但是根據您的原始表達式,我猜測這可能是我們可能希望以i標志開頭的內容:

^[A-Z ]{3,}-\d{1,6}$

或沒有i標記:

^[A-Za-z ]{3,}-\d{1,6}$

演示

測試

 const regex = /^[AZ ]{3,}-\\d{1,6}$/gmi; const str = `Some Text-1 Some Text-201901 Some Text-20190101`; let m; while ((m = regex.exec(str)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } // The result can be accessed through the `m`-variable. m.forEach((match, groupIndex) => { console.log(`Found match, group ${groupIndex}: ${match}`); }); } 

正則表達式

如果不需要此表達式,則可以在regex101.com中對其進行修改/更改。

RegEx電路

jex.im可視化正則表達式:

在此處輸入圖片說明

暫無
暫無

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

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