Can I use the Or operator in a regular expression to validate input?

I am learning how to use regular expressions to validate user inputs. I am using jQuery for this. I just want to know if the OR operator can be used inside an expression.

I want to check if there is a line:

  • One letter first and then at least 6 digits

OR

  • At least 6 digits first, then one letter

Examples:

X123456... OR 123456P 

I use this /^[a-zA-Z]\d{6}/ for the first, but can I use something like this to take into account both conditions?

 /^[a-zA-Z]\d{6}/ | /^\d{6}/[a-zA-Z] ?? 

thanks for the help

+4
source share
3 answers

You almost got it:

 /^(?:[a-zA-Z]\d{6,}|\d{6,}[a-zA-Z])/ 

| is an alternation algorithm

+3
source

Regular expressions have an alternate operator that uses the same character | . You just need to put it in regexp:

 /^([az]\d{6}|\d{6}[az])/i 
+2
source

Yes, of course, you are very much there:

 /^([a-zA-Z]\d{6}|\d{6}[a-zA-Z])/ 
+1
source

Source: https://habr.com/ru/post/1494693/


All Articles