Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match only two specific words, e.g. Yes or No

Tags:

regex

My attempt is:

^Yes|^No|^$ 

but when I use this, words other than "Yes" and "No" are matched

How do I fix it?

I've been testing my regex using this online regex tester.

like image 253
Konrad Avatar asked Jun 27 '14 06:06

Konrad


2 Answers

Try this:

^(?:Yes|No)$

In VBScript, something like this:

Dim myRegExp, FoundMatch
Set myRegExp = New RegExp
myRegExp.Pattern = "^(?:Yes|No)$"
FoundMatch = myRegExp.Test(SubjectString)

What was the problem?

You had an alternation with three options:

  • ^Yes matches Yes at the beginning of the string, but will also match Yes in Yes, man...
  • ^No matches No at the beginning of the string, but will also match No in No way!
  • ^$ matches the empty string
like image 101
zx81 Avatar answered Sep 22 '22 12:09

zx81


Below regex would match yes or no only,

^(?:Yes\b|No\b)

Demo

like image 26
Avinash Raj Avatar answered Sep 18 '22 12:09

Avinash Raj