[英]Regex to match '-' delimited alphanumeric words
我想測試用戶是否僅鍵入字母數字值或一個“-”。
hello-world -> Match
hello-first-world -> match
this-is-my-super-world -> match
hello--world -> NO MATCH
hello-world-------this-is -> NO MATCH
-hello-world -> NO MATCH (leading dash)
hello-world- -> NO MATCH (trailing dash)
到目前為止,這是我所擁有的,但我不知道如何實現“-”號來測試它是否只有一次而不重復。
var regExp = /^[A-Za-z0-9-]+$/;
嘗試這個:
/^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$/
這將僅匹配由單個-
分隔的一個或多個字母數字字符序列的序列。 如果您不想允許單個單詞(例如,只是hello
),請將*
乘數替換為+
以僅允許最后一個組的一次或多次重復。
你去(這是有效的)。
var regExp = /^[A-Za-z0-9]+([-]{1}[A-Za-z0-9]+)+$/;
字母和數字貪婪,單個破折號,重復此組合,以字母和數字結尾。
(^-)|-{2,}|[^a-zA-Z-]|(-$)
查找無效字符,因此與該模式的零匹配將滿足您的要求。
我不完全確定這是否有效,因為我有一段時間沒有使用正則表達式,但聽起來你需要以下內容:
/ ^ [A-ZA-Z0-9] +( - [A-ZA-Z0-9] +)+ $ /
您的要求分為以下幾種:
我只是不確定我是否正確地使用正則表達式來遵循該格式。
表達式可以簡化為: /^[^\W_]+(?:-[^\W_]+)+$/
解釋:
^ match the start of string
[^\W_]+ match one or more word(a-zA-Z0-9) chars
(?:-[^\W_]+)+ match one or more group of '-' follwed by word chars
$ match the end of string
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.