Xi 张熹
Xi 张熹

Reputation: 11071

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

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

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,

Upvotes: 19

Views: 56064

Answers (4)

chx
chx

Reputation: 11790

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})`);

This simply combines the two patterns with a pipe | character, which indicates alternative matches. Each pattern is also wrapped in parentheses to group them.

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

Upvotes: 19

Irshad Khan
Irshad Khan

Reputation: 6046

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

This are the signs to combine, in order of relevance:

*? example 1 : (A)*?(B)

| example 2 : A|B

()() example 3 : (A)(B)

()|() example 4 : (A)|(B)

Upvotes: 1

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

Upvotes: 11

Jordan
Jordan

Reputation: 5058

Not sure which language you are using to implement but you can use a single | to use a logical or most regex. My suggestion would be to store each regex as a string and then concatenate and compile when necessary.

in python it would be something like

visa = "visa_regex"
mastercard = "mastercard_regex"
combined = re.compile(visa + "|" + mastercard)

Upvotes: 3

Related Questions