簡體   English   中英

不包含連續字符的正則表達式

[英]Regex for not containing consecutive characters

我想不出滿足所有這些要求的 javascript 正則表達式:

字符串只能包含下划線和字母數字字符。 它必須以字母開頭,不能包含空格,不能以下划線結尾,並且不能包含兩個連續的下划線。

這是就我而言,但“不包含連續下划線”部分是最難添加的。

^[a-zA-Z][a-zA-Z0-9_]+[a-zA-Z0-9]$

您可以使用多個前瞻(在這種情況下為否定):

^(?!.*__)(?!.*_$)[A-Za-z]\w*$

在 regex101.com 上查看演示


分解這說:

 ^ # start of the line (?!.*__) # neg. lookahead, no two consecutive underscores (edit 5/31/20: removed extra Kleene star) (?!.*_$) # not an underscore right at the end [A-Za-z]\\w* # letter, followed by 0+ alphanumeric characters $ # the end


作為JavaScript片段:

 let strings = ['somestring', '_not_this_one', 'thisone_', 'neither this one', 'but_this_one', 'this__one_not', 'this_one__yes'] var re = /^(?!.*__)(?!.*_$)[A-Za-z]\\w*$/; strings.forEach(function(string) { console.log(re.test(string)); });

請不要限制密碼!

你也可以使用

^[a-zA-Z]([a-zA-Z0-9]|(_(?!_)))+[a-zA-Z0-9]$

演示

與您的正則表達式相比,唯一的變化是將[a-zA-Z0-9_]更改為[a-zA-Z0-9]|(_(?!_)) 我從字符集中刪除了下划線,如果后面沒有另一個下划線,則允許它出現在備選方案的第二部分。

(?!_)是負前瞻意味着_不能是下一個字符

請參閱此處使用的正則表達式

^[a-z](?!\w*__)(?:\w*[^\W_])?$
  • ^斷言位置作為行的開始
  • [az]匹配任何小寫 ASCII 字母。 下面的代碼添加了i (不區分大小寫)標志,因此這也匹配大寫變量
  • (?!\\w*__)負前瞻確保字符串中不存在兩個下划線
  • (?:\\w*[^\\W_])? 可選匹配以下內容
    • \\w*匹配任意數量的單詞字符
    • [^\\W_]匹配除_之外的任何單詞字符。 解釋:匹配任何 不是 單詞字符但不是_ (因為它在否定集中)。
  • $斷言行尾位置

 let a = ['somestring', '_not_this_one', 'thisone_', 'neither this one', 'but_this_one', 'this__one_not', 'this_one__yes'] var r = /^[az](?!\\w*__)(?:\\w*[^\\W_])?$/i a.forEach(function(s) { if(r.test(s)) console.log(s) });

甚至更簡單的版本,沒有環視(因此也可用於不支持它們的正則表達式風格,例如 POSIX ERE,甚至sed風格的正則表達式,只需簡單更改):

^[a-zA-Z](_?[a-zA-Z0-9]+)*$

暫無
暫無

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

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