admin管理员组

文章数量:1026989

I need to write a regex for validating a string. The regular expression should pass the string if it contains any of the following: y, Y, yes, YES, 1. The letters can be in any case. I am new to regular expression and JavaScript.

I need to write a regex for validating a string. The regular expression should pass the string if it contains any of the following: y, Y, yes, YES, 1. The letters can be in any case. I am new to regular expression and JavaScript.

Share Improve this question edited Aug 24, 2015 at 2:11 Alan Moore 75.3k13 gold badges107 silver badges161 bronze badges asked Aug 17, 2015 at 5:24 Hitesh KumarHitesh Kumar 3,7089 gold badges48 silver badges73 bronze badges 3
  • 2 Have you tried anything? Looks simple – Tushar Commented Aug 17, 2015 at 5:25
  • 'hello y here is yes i am Y you are Yes'.match(/yes|y|1/gi) remove g if you know that only one of them exists – Harpreet Singh Commented Aug 17, 2015 at 5:27
  • contains any of the following: do you mean "contains", or do you mean "exactly equal to"? – user663031 Commented Aug 24, 2015 at 2:38
Add a ment  | 

1 Answer 1

Reset to default 9

You need to add an optional group as well as a case-insensitive i modifier.

/y(?:es)?|1/i.test(str)

or

/[1y](?:es)?/i.test(str)

or

/[y1]/i.test(str)

For doing exact match.

/^(?:y(?:es)?|1)$/i.test(str)

I need to write a regex for validating a string. The regular expression should pass the string if it contains any of the following: y, Y, yes, YES, 1. The letters can be in any case. I am new to regular expression and JavaScript.

I need to write a regex for validating a string. The regular expression should pass the string if it contains any of the following: y, Y, yes, YES, 1. The letters can be in any case. I am new to regular expression and JavaScript.

Share Improve this question edited Aug 24, 2015 at 2:11 Alan Moore 75.3k13 gold badges107 silver badges161 bronze badges asked Aug 17, 2015 at 5:24 Hitesh KumarHitesh Kumar 3,7089 gold badges48 silver badges73 bronze badges 3
  • 2 Have you tried anything? Looks simple – Tushar Commented Aug 17, 2015 at 5:25
  • 'hello y here is yes i am Y you are Yes'.match(/yes|y|1/gi) remove g if you know that only one of them exists – Harpreet Singh Commented Aug 17, 2015 at 5:27
  • contains any of the following: do you mean "contains", or do you mean "exactly equal to"? – user663031 Commented Aug 24, 2015 at 2:38
Add a ment  | 

1 Answer 1

Reset to default 9

You need to add an optional group as well as a case-insensitive i modifier.

/y(?:es)?|1/i.test(str)

or

/[1y](?:es)?/i.test(str)

or

/[y1]/i.test(str)

For doing exact match.

/^(?:y(?:es)?|1)$/i.test(str)

本文标签: javascriptRegular expression for yyesY1Stack Overflow