【问题标题】:Usernames that cannot start or end with characters不能以字符开头或结尾的用户名
【发布时间】:2018-08-13 00:58:06
【问题描述】:

我正在尝试使用正则表达式来实现这些规则:

  • 可以包含大小写字母和数字
  • 可以包含下划线和句点
  • 不能连续包含 2 个下划线
  • 不能连续包含 2 个句点
  • 不能以下划线或句点开头或结尾
  • 不能包含带重音符号的字母
  • 长度必须在 3 到 28 个字母之间

有效:

Spicy_Pizza
97Indigos
Infinity.Beyond

无效:

_yahoo
powerup.
un__real
no..way

这是我当前的正则表达式:

^(?:[a-zA-Z0-9]|([._])(?!\1)){3,28}$

除了以下划线或句点开头和结尾的例外,所有规则似乎都有效。

【问题讨论】:

  • 你的问题是什么?

标签: ruby regex


【解决方案1】:

听起来您只需要在字符串的第一个和最后一个字符上添加一个字母数字检查。因为这将占用 2 个字符,所以将内部重复从 {3,28} 更改为 {1,26}:

^[A-Za-z\d](?:[a-zA-Z0-9]|([._])(?!\1)){1,26}[A-Za-z\d]$
 ^^^^^^^^^^                             ^^^^ ^^^^^^^^^^

https://regex101.com/r/G6bVaZ/1

【讨论】:

  • ^ 和 $ 匹配 Ruby 中 line 的开头/结尾,您几乎总是希望使用 \A 和 \z(分别)因为那些在 string. 的开头/结尾匹配
【解决方案2】:

我更喜欢明确字符串不能以句点或下划线开头或结尾,而不是规定字符串的开头和结尾允许使用哪些字符。

r = /
    \A            # match beginning of string
    (?![._])      # next char cannot be a period or underscore
    (?:           # begin non-capture group
      [a-zA-Z0-9] # match one of chars in indicated
      |           # or
      ([._])      # match a period or underscore in capture group 1
      (?!\1)      # next char cannot be the contents of capture group 1
    ){3,28}       # end non-capture group and execute non-capture group 3-28 times
    (?<![._])     # previous char cannot be a period or underscore
    \z            # match end of string
    /x            # free-spacing regex definition mode

%w| Spicy_Pizza 97Indigos Infinity.Beyond _yahoo powerup. un__real no..way |.each do |s|
  puts "%s: %s" % [s, s.match?(r) ? "valid" : "invalid"]
end

Spicy_Pizza:     valid
97Indigos:       valid
Infinity.Beyond: valid
_yahoo:          invalid
powerup.:        invalid
un__real:        invalid
no..way:         invalid

【讨论】:

    猜你喜欢
    • 2019-01-26
    • 2022-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 2020-10-08
    • 2018-02-18
    相关资源
    最近更新 更多