Andreas Hunter
Andreas Hunter

Reputation: 5004

Why doesn’t work when regex entering 1 letter after the optional character?

I've custom regex pattern for check correct username on url:

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

This pattern work when I write usernames:

@username
@username_16
@username16

But not work when I write:

@u

First part of question:
How to rewrite this pattern for work in @u?

Second part of question:
How control characters limit or length after @ symbol?

Upvotes: 1

Views: 46

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626754

The [a-z] and [a-z0-9] are obligatory patterns inside the optional group, hence if there is something after @, there must be two chars at least.

Besides, your regex also matches a string that equals @.

To fix all these issues you may use

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

See the regex demo.

Now, to restrict the length of a string after @ symbol, you may insert a (?=.{x,m}$) positive lookahead right after @. Say, to only match 3 or 4 chars after @, use:

^@(?=[a-z0-9_]{3,4}$)[a-z](?:[a-z0-9_]*[a-z0-9])?$
  ^^^^^^^^^^^^^^^^^^^    

Or, since the consuming pattern will validate the rest

^@(?=.{3,4}$)[a-z](?:[a-z0-9_]*[a-z0-9])?$
  ^^^^^^^^^^^

See this regex demo

Details

  • ^ - start of string
  • (?=.{3,4}$) - a positive lookahead that requires any 3 or 4 chars other than line break chars up to the end of the string immediately to the right of the current location (i.e. from the string start here)
  • @ - a @ char
  • [a-z] - a lowercase ASCII letter
  • (?:[a-z0-9_]*[a-z0-9])? - an optional non-capturing group matching 1 or 0 occurrences of
    • [a-z0-9_]* - 0+ lowercase ASCII letters, digits or _
    • [a-z0-9] - a lowercase ASCII letter or digits
  • $ - end of string.

Upvotes: 2

Related Questions