Home > database >  How can I write the Javascript Regular Expression pattern to handle these conditions
How can I write the Javascript Regular Expression pattern to handle these conditions

Time:12-11

In My exercise, I'm given a task to write a regular expression pattern that validates username input for storage into database.

Usernames can only use alpha-numeric characters.

The only numbers in the username have to be at the end. There can be zero or more of them at the end. Username cannot start with the number.

Username letters can be lowercase and uppercase.

Usernames have to be at least two characters long. A two-character username can only use alphabet letters as characters.

I succeeded to pass all tests except one

A1 is not supposed to match the patern

let userCheck = /^[A-Za-z] \w\d*$/;
let result = userCheck.test(username);

CodePudding user response:

This works for your description:

let userCheck = /^[A-Za-z]{2,}\d*$/;
let result = userCheck.test(username);

Let me explain what went wrong in your regex:

/^[A-Za-z] \w\d*$/

You correctly match, that the first character is only a letter. The ' ' however only ensures, that it is matched at least one time. If you want to match something an exact number of times, you can append '{x}' to your match-case. If you rather want to match a minimum and maximum amount of times, you can append '{min, max}'. In your case, you only have a lower limit (2 times), so the max stays empty and means unlimited times: {2,}

After your [2 - unlimited] letters, you want to have [0 - unlimited] numbers. '\w' also matches letters, so we can just remove it. The end of your regex was correct, as '\d' matches any digit, and '*' quantifies the previous match for the range [0 - unlimited].

I recommend using regex101.com for testing and developing regex patterns. You can test your strings and get very good documentation and explanation about all the tags. I added my regex with some example strings to this link: https://regex101.com/r/qPmwhG/1

The strings that match will be highlighted, the others stay without highlighting.

CodePudding user response:

You could write the pattern as:

^[a-zA-Z]{2,}\d*$

Explanation

  • ^ Start of string
  • [a-zA-Z]{2,} Match 2 or more times a char a-zA-Z
  • \d* Match optional digits
  • $ End of string

Regex demo

  • Related