Vicky Kumar
Vicky Kumar

Reputation: 81

regex for string which consist of 1 to 4 non-zero numeric characters or 1 to 4 non-zero numeric characters and 1 alphabet

I am writing a regex for strings that consist of 1 to 4 non-zero numeric characters or 1 to 4 non-zero numeric characters and 1 alphabetic, but I am stuck in how to fix length of the alphabetic characters to one.

"(^[1-9]{1,4}$|^[[a-zA-Z][1-9]{1,4}]$)"

I tried this way, but its not working; it is validating only strings that consist of 1 to 4 non-zero numeric characters.

Upvotes: 3

Views: 71

Answers (2)

vks
vks

Reputation: 67968

^(?:\d{1,4}|(?=\d*[a-zA-Z]\d*$)[\da-zA-Z]{2,5})$

You need a lookahead for this.See demo.

https://regex101.com/r/eX9gK2/2

Upvotes: 2

Ugo Stephant
Ugo Stephant

Reputation: 140

Generally, your best chance is to test your regex using an online tool, like http://www.regexr.com/.

Besides, what you're trying to achieve can be done like this : ([a-zA-Z]?[1-9]{1,4})

Explanations :

  • [a-zA-Z] Means a-z alphabetical character
  • ? Means 0 or 1 of the previous set (what was missing in your test)
  • [1-9]{1,4} Means 1 to 4 numerical characters, as you mention it

Upvotes: 0

Related Questions