Skip to content
Advertisement

Regex for letters and numbers with any underscores in between

I’m trying to create a Regex String with the following rules

  1. The username is between 4 and 25 characters.
  2. It must start with a letter.
  3. It can only contain letters, numbers, and the underscore character.
  4. It cannot end with an underscore character.

when it meets this criterion I want the output to be true otherwise false, but I only get false for my test cases, here is my code

JavaScript

Main class

JavaScript

input

JavaScript

output

JavaScript

Fixed: thanks to everyone who contributed

Advertisement

Answer

You can use

JavaScript

See the regex demo.

Details:

  • ^ – start of string
  • [a-zA-Z] – an ASCII letter
  • [a-zA-Z0-9_]{3,24} / w{3,24} – three to twenty four ASCII letters, digits or underscores
  • $ – end of string
  • (?<!_) – a negative lookbehind that makes sure there is no _ (at the end of string).

Note that {3,24} is used and not {4,25} because the first [a-zA-Z] pattern already matches a single char.

Usage:

JavaScript

See Java demo:

JavaScript
Advertisement