![](/img/trans.png)
[英]Need Javascript Regex to prevent user to enter only characters and only one apostrophe allowed
[英]Js Regex only allowed characters one occurence
非常努力地嘗試正則表達式,但無法獲得預期的結果。
請看下面的代碼。
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.