javascript - RegEx to identify guid or a number - Stack Overflow

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}$iAnd r

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 badges
Add a ment  | 

3 Answers 3

Reset to default 3

Use | 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
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744834847a4596200.html

相关推荐

  • javascript - RegEx to identify guid or a number - Stack Overflow

    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}$iAnd r

    2天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信