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

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

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.