3

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.

3 Answers3

3

Use | in a regular expression to match either what comes before or what comes 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]);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
2

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]*$)/
Rajat
  • 71
  • 5
0

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
}
31piy
  • 23,323
  • 6
  • 47
  • 67