1

I need to validate an input that must start with an alpha, and then it can be alphanumeric, but once numeric; it must be numeric to the end of the string.

[a-z][a-z,0-9]{1,5}

This does only part of the job. So it validates correctly for

a1
abc12
ab123

but I do not want

a1b2c1

so onces it gets a numeric, the rest must be numeric.

5
  • [a-z][a-z]{1,5}[0-9]{1,5}. Not exactly what you want but you can try
    – JSmith
    Commented Mar 27, 2020 at 2:19
  • Do you really want a comma in your character class?
    – Nick
    Commented Mar 27, 2020 at 2:25
  • Is the string required to be 2 to 6 characters long?
    – Nick
    Commented Mar 27, 2020 at 2:27
  • Yes, the string is to be 2 to 6 characters, so 'a1' is valid so is 'ab1234'; but not a12b2, so the instance when a numeric appears, the the rest (if any must be a numeric)
    – munchine
    Commented Mar 27, 2020 at 3:05
  • The comma was an error, thanks for pointing that out
    – munchine
    Commented Mar 27, 2020 at 3:12

2 Answers 2

1

Try this:

^(?=.{2,6}$)([a-z]+[0-9]*)$

First check for 2-6 characters from beginning to end of line. It doesn't even matter what characters they are - you are just checking for length.

Then, 1 or more letters followed by any number of numbers. Since you already checked for 2-6 characters only you don't really care how many letters are followed by how many numbers. At first, I thought it would be much more complicated to list all the possibilities but the positive lookahead does alot of the work

See https://regex101.com/r/HYQIf6/5

0

This should work for a string of any length:

^[a-z]+([a-z]*|\d*)$

This will return true if the string:

  • starts with one or more letters from a to z
  • followed by zero or more: letters or numbers until the end

See the matches at Regex101

Edit:

This works as well:

^[a-z]+\d*$

See new regex

3
  • From the comment by the OP: "Yes, the string is to be 2 to 6 characters".
    – Mark
    Commented Mar 27, 2020 at 3:58
  • @Mark, Sure, but since it works for strings with any number of characters it also works for 2 to 6 characters. You can test the length separately. And being a simple regex it is easy to maintain in case the rules change. Also, it doesn't have any lookahead. Commented Mar 27, 2020 at 4:01
  • If you are using a separate check for length, just use ^([a-z]+[0-9]*)$.
    – Mark
    Commented Mar 27, 2020 at 4:10

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.