4.11. Validate Affirmative Responses
Problem
You need to check a configuration option or command-line
response for a positive value. You want to provide some flexibility in
the accepted responses, so that true, t, yes, y, okay, ok, and 1 are all accepted in any combination of
uppercase and lowercase.
Solution
Using a regex that combines all of the accepted forms allows you to perform the check with one simple test.
Regular expression
^(?:1|t(?:rue)?|y(?:es)?|ok(?:ay)?)$
| Regex options: Case insensitive |
| Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
JavaScript example
var yes = /^(?:1|t(?:rue)?|y(?:es)?|ok(?:ay)?)$/i;
if (yes.test(subject)) {
alert("Yes");
} else {
alert("No");
}Follow Recipe 3.6 to run this regex with other programming languages. Recipe 3.4 shows how to apply the “case insensitive” regex option, among others.
Discussion
The following breakdown shows the individual parts of the regex. Combinations of tokens that are easy to read together are shown on the same line:
^ # Assert position at the beginning of the string. (?: # Group but don't capture: 1 # Match "1". | # Or: t(?:rue)? # Match "t", optionally followed by "rue". | # Or: y(?:es)? # Match "y", optionally followed by "es". | # Or: ok(?:ay)? # Match "ok", optionally followed by "ay". ) # End the noncapturing group. $ # Assert position at the end of the string.
| Regex options: Case insensitive, free-spacing |
| Regex flavors: .NET, Java, XRegExp, PCRE, Perl, Python, Ruby |
This regex is essentially a simple test for ...