簡體   English   中英

Js Regex 只允許字符出現一次

[英]Js Regex only allowed characters one occurence

非常努力地嘗試正則表達式,但無法獲得預期的結果。

  1. 必須以數字開頭,最多 4 個
  2. 后面只有一個允許的字母

請看下面的代碼。

 var strings = [ '1h', //should match '13s', //should match '30m', //should match '42hr', //should not match '8 hours ', //should not match '765765', //should not match '5sec', //should not match '23445345345s', //should not match '335m' //should match ]; for (var i = 0; i < strings.length; i++) { var match = strings[i].match(/\d{4}[h|m|s]{1}/g); console.log(strings[i], (match? "Match": "Not match")); }

你的正則表達式應該是:

/^\d{1,4}[h|m|s]{1}$/gm

首先,您需要 4 位數字和d{4}

將其更改為d{1,4}為一到四位數

然后加一個$來表示字符串的結尾,這樣就不允許字母后面有更多字符了

查看Regex101 ,對於測試和理解正則表達式非常有用

我添加了一個 ^ 以從頭開始匹配

strings.filter(x =>  x.match(/^\d{1,4}[h|m|s](?!\w)/g)  )

暫無
暫無

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

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