florianste
florianste

Reputation: 13

RegEx for matching only digits and a maximum of 3 characters

Can someone give me a hint why the following RegEx doesn’t work? I‘m trying to validate a string that must contain at least one number 0-9 at the beginning or the end and maximum 3 characters (A-Z) and including whitespaces. I‘ve tried:

^[0-9]{1,}\s*\w{0,3}|\w{0,3}\s*[0-9]{1,}

But the RegEx above matches everything that contains those characters. But I want to make sure that it matches only if no more than desired characters and numbers are in my string.

Should return true:

Should return false:

I‘d really appreciate it if someone could give me a hint.

Upvotes: 1

Views: 176

Answers (1)

mario
mario

Reputation: 145482

There's a couple of things:

  • You are only anchoring ^ the first alternative.

  • And you probably should be using $ as well, if you want to assert the whole string.

  • Else the second |\w{0,3}\s* alternative might match anywhere (and would also match an empty string really)

  • Furthermore, make this more readable with \d+ instead of [0-9]{1,}

  • But more strict for [A-Z][0,3} instead of \w (might match numbers).

So in essence:

/^(
     \d+ \s* [A-Z]{0,3}    # 123 ABC
  |
     [A-Z]{0,3} \s* \d+    # ABC 123
  )$
/ix   # /x flag for readability

Upvotes: 1

Related Questions