Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I "combine" 2 regex with a logic or?

Tags:

regex

I need to validate Textbox input as credit card number. I already have regex for different credit cards:

  • Visa: ^4[0-9]{12}(?:[0-9]{3})?$
  • Mastercard: ^([51|52|53|54|55]{2})([0-9]{14})$
  • American Express: ^3[47][0-9]{13}$

and many others.

The problem is, I want to validate using different regex based on different users. For example: For user1, Visa and Mastercard are available, while for user2, Visa and American Express are available. So I would like to generate a final regex string dynamically, combining one or more regex string above, like:

user1Regex = Visa regex + "||" + Mastercard regex

user2Regex = Visa regex + "||" + American Express regex

Is there a way to do that? Thanks,

like image 379
Xi 张熹 Avatar asked Feb 09 '11 16:02

Xi 张熹


People also ask

How do I combine two regex expressions?

to combine two expressions or more, put every expression in brackets, and use: *?

Can you use or in regex?

Alternation is the term in regular expression that is actually a simple “OR”. In a regular expression it is denoted with a vertical line character | . For instance, we need to find programming languages: HTML, PHP, Java or JavaScript.

How do you use two regular expressions in Python?

made this to find all with multiple #regular #expressions. regex1 = r"your regex here" regex2 = r"your regex here" regex3 = r"your regex here" regexList = [regex1, regex1, regex3] for x in regexList: if re. findall(x, your string): some_list = re. findall(x, your string) for y in some_list: found_regex_list.


2 Answers

You did not state your language but for whatever reason I suspect it's JavaScript. Just do:

var user1Regex = new RegExp('(' + Visaregex + ")|(" + Mastercardregex + ')');
// or if es6:
let user1Regex = new RegExp(`(${Visaregex})|(${Mastercardregex})`);

You can also use (?:) for speedier execution (non-capturing grouping) but I have omitted that for readability.

like image 178
chx Avatar answered Sep 23 '22 12:09

chx


Use the | operator and group all with parentesis ()

^(4[0-9]{12}(?:[0-9]{3})?|([51|52|53|54|55]{2})([0-9]{14})|3[47][0-9]{13})$

If all regex are correct it should work

like image 38
Gustavo Costa De Oliveira Avatar answered Sep 22 '22 12:09

Gustavo Costa De Oliveira