I have regex for guid:
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
And regex to match a number:
/^[0-9]*$
But I need to match either a guid or a number. Is there a way to do it matching a single regex. Or should I check for guid and number separately.
I have regex for guid:
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
And regex to match a number:
/^[0-9]*$
But I need to match either a guid or a number. Is there a way to do it matching a single regex. Or should I check for guid and number separately.
Share Improve this question asked Apr 20, 2018 at 4:37 Gabriela JenniferGabriela Jennifer 1193 silver badges13 bronze badges3 Answers
Reset to default 3Use |
in a regular expression to match either what es before or what es after:
const re = /^([0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})|[0-9]+$/i;
console.log('11111111-1111-1111-8111-111111111111'.match(re)[0]);
console.log('5555'.match(re)[0]);
You can use | operator between two regex expressions. You can use them as given below
/(^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i) | (^[0-9]*$)/
Yes, there are many ways for this. One is to OR the matches in an if
statement:
var reg1 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
var reg2 = /^[0-9]*$/;
var text = " ... ";
if (reg1.test(text) || reg2.test(text)) {
// do your stuff here
}
Another approach is ORing in the RegExp itself:
var regex = /(^[0-9]*)|^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
var text = " ... ";
if (regex.test(text)) {
// do your stuff here
}