gpt4 book ai didi

regex - 允许 A-Za-z0-9 的 Ruby 正则表达式

转载 作者:数据小太阳 更新时间:2023-10-29 07:25:24 25 4
gpt4 key购买 nike

我有以下正则表达式:

/([A-Za-z0-9]+)([A-Za-z0-9\-\_]+)([A-Za-z0-9]+)/

它不符合我的需要,它们是:

  • 不允许有空格
  • 允许大写英文字母
  • 允许小写英文字母
  • 允许数字
  • 字符串不能同时包含连字符和下划线
  • 连字符:连字符不能在字符串的开头或结尾;可以有任意数量的连字符,但连续只能有 1 个连字符(a--b 无效)。
  • 下划线:下划线不能在字符串的开头或结尾;可以有任意数量的下划线,但连续只能有 1 个下划线(a__b 无效)
  • 字符串必须至少包含1个字符(字母)

有效示例:

  • a1_b_2_hello
  • 2b-ffg-er2
  • abs
  • 123a

无效示例:

  • _a1_b_2_hello
  • 2b-ffg_er2-
  • __
  • --
  • a__
  • b--2

最佳答案

我发现将所有特殊条件放在正面和负面前瞻的开头很方便,然后在这些条件(不消耗任何字符)后面加上一般要求,此处 [a-z\d_-]+\z

r = /
\A # match start of string
(?!.* # begin negative lookahead and match >= 0 characters
(?:--|__) # match -- or __ in a non-capture group
) # end negative lookahead
(?![-_]) # do not match - or _ at the beginning of the string
(?!.*[-_]\z) # do not match - or _ at the end of the string
(?! # begin negative lookahead
.*-.*_ # match - followed by _
| # or
.*_.*- # match _ followed by -
) # end negative lookahead
(?=.*[a-z]) # match at least one letter
[a-z\d_-]+ # match one or more English letters, digits, _ or -
\z # match end of string
/ix # case indifference and free-spacing modes

 "a".match? r          #=> true   
"aB32-41".match? r #=> true
"".match? r #=> false (must match a letter)
"123-4_5".match? r #=> false (must match a letter)
"-aB32-4_1".match? r #=> false (cannot begin with -)
"aB32-4_1-".match? r #=> false (cannot end with -)
"_aB32-4_1".match? r #=> false (cannot begin with _)
"aB32-4_1_".match? r #=> false (cannot end with _)
"aB32--4_1".match? r #=> false (cannot contain --)
"aB32-4__1".match? r #=> false (cannot contain __)
"aB32-4_1".match? r #=> false (cannot contain both - and _)
"123-4_5$".match? r #=> false ($ is not a permitted character)

这个正则表达式按照惯例写成:

/\A(?!.*(?:--|__))(?![-_])(?!.*[-_]\z)(?!.*-.*_|.*_.*-)(?=.*[a-z])[a-z\d_-]+\z/i

关于regex - 允许 A-Za-z0-9 的 Ruby 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57433463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com