我可以“组合"吗?2 正则表达式与逻辑或? [英] 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:
- 签证:
^4[0-9]{12}(?:[0-9]{3})?$
- 万事达卡:
^([51|52|53|54|55]{2})([0-9]{14})$
- 美国运通:
^3[47][0-9]{13}$
和许多其他人.
问题是,我想根据不同的用户使用不同的正则表达式进行验证.例如:user1 可以使用Visa 和Mastercard,而user2 可以使用Visa 和American Express.所以我想动态生成一个最终的正则表达式字符串,结合上面的一个或多个正则表达式字符串,比如:
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,
推荐答案
您没有说明您的语言,但无论出于何种原因,我怀疑它是 JavaScript.就这样做:
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.
这篇关于我可以“组合"吗?2 正则表达式与逻辑或?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!