【问题标题】:Regular Expression pattern for alphanumeric username字母数字用户名的正则表达式模式
【发布时间】:2021-11-26 00:14:18
【问题描述】:

我想将用户名输入为字母数字字符串

  • 字母和数字都应该是字符串。
  • 字符串应以字母开头,以数字结尾。
  • 它只能包含下划线作为特殊字符(可选)。

我的代码

 <input type="text" name="username" id="username" placeholder="Choose Username" 
  pattern="^[a-zA-Z0-9_]+${7,25}" autocomplete="off" required>

【问题讨论】:

  • 使用pattern="(?=\D*\d)(?=[^A-Za-z]*[A-Za-z])[a-zA-Z]\w{5,23}\d"
  • 请更加准确,并提供一些有效和无效用户名的示例。例如,"abc123def456" 是否有效,或者字母前面不能有数字?此外,您在问题中没有提及{7,25} 的必要性,尽管我认为这是指用户名的所需长度。
  • 如果字符串应该以字母开头,并以数字结尾,那么“理论上”这个要求 both letters and numbers should be in string 已经使用 pattern="[a-zA-Z]\w{5,23}\d" 满足了或者这不是你的意思吗?

标签: html regex forms validation input


【解决方案1】:

您需要积极的前瞻性

https://regex101.com/r/280p8a/1

^(?=\w{7,25}$)[A-Za-z]\w+\d$)

Positive Lookahead (?=^.{7,25}$)
Assert that the Regex below matches
^ asserts position at start of a line
\w matches any word character ([a-zA-Z0-9_])
{7,25} matches the previous token between 7 and 25 times, as many times as possible, giving back as needed (greedy)
$ asserts position at the end of a line

【讨论】:

  • 字符串只能包含单词字符,您可以将锚点放在前瞻之外的开头,然后在断言中使用 \w 而不是 . 如果它匹配非单词字符。您也可以省略匹配的捕获组。 ^(?=\w{7,25}$)[A-Za-z]\w+\d$
  • @Thefourthbird 大进步
猜你喜欢
  • 2011-09-16
  • 1970-01-01
  • 2014-01-31
  • 2014-05-24
  • 2020-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多