doy2255 2018-10-16 09:41
浏览 422
已采纳

如何重写我的正则表达式匹配正确的用户昵称?

I have sample regex for check user nickname:

^[a-z][a-z0-9_](?:[a-z0-9]+)*$

This regex match correct nicknames:

  1. username
  2. username16

But can't match like this correct nicknames:

  1. username_16

In generaly how rewrite my regex for regx which can ignore sample wrong user names:

  1. 16username
  2. _username
  3. username_

User nickname string on start can contain only a-z letters and in the middle (center) of string can contain a-z0-9_ and on the end can contain only a-z0-9

  • 写回答

1条回答 默认 最新

  • dqjjw04440 2018-10-16 09:43
    关注

    You may use

    ^[a-z](?:[a-z0-9_]*[a-z0-9])?$
    

    See the regex demo.

    Details

    • ^ - start of string
    • [a-z] - a lowercase ASCII letter
    • (?:[a-z0-9_]*[a-z0-9])? - an optional sequence (it will make possible to match 1-char input) of
      • [a-z0-9_]* - 0+ lowercase letters, digits or _
      • [a-z0-9] - a lowercase ASCII letter or digit
    • $ - end of string

    If there is a limit to the minimum chars in the input more than 1, you may remove the optional capturing group parentheses/quantifier and use

    ^[a-z][a-z0-9_]*[a-z0-9]$
    

    And vice versa, to also allow an empty string, wrap with another optional group:

    ^(?:[a-z](?:[a-z0-9_]*[a-z0-9])?)?$
     ^^^                            ^^
    

    There may be other ways to write the pattern, e.g.

    ^(?=[a-z])[a-z0-9_]*$(?<=[a-z0-9])
    

    that will match a string consisting of lowercase letters, digits or _ where the first char must be a lowercase letter and the last one should be either a letter or a digit.

    See this regex demo.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站