Regex to match "True" or "False"

I need to create Regular Expression validator which will need to match a text "True" or "False" (Case Insensitive).

I have tried the following regex

^(True|False|TRUE|FALSE)$

Is this correct? but there is problem in Case Sensitive.

Edit

I have tried regex in following answers but it's not firing, because of ?i

0

5 Answers

Either use RegexOptions.IgnoreCase

or the inline ?i modifier

^(?i)(true|false)$
1

I have checked all the answers in this post but nothing worked as expected.

I Guess ?i is not supported in Asp.Net RegularExpression validator.

Finally I used following regex.

^([Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee])$

It worked as expected.

This regex will be used for dynamically created Asp.net RegularExpressionvalidator.

7

With a small optimization:

^(?:tru|fals)e$

Since (?i) is not validating, we'll set the case insensitivity in the code.

For any future reader who needs the code:

Dim FoundMatch As Boolean
Try FoundMatch = Regex.IsMatch(SubjectString, "^(?:tru|fals)e$", RegexOptions.IgnoreCase)
Catch ex As ArgumentException 'Syntax error in the regular expression
End Try
3

Use RegexOptions.IgnoreCase option and use the below regex:

^(true|false)$

or use ignore case modifer ?i

Like this:

^(?i:true|false)$

Another option would be to convert the string to lower case and just use ^(true|false)$

1

Another approach for words True or False:

If Boolean.TryParse(yourString, New Boolean) = true Then 'ok
else 'not ok
End If

If you want convert text to boolean variable and use it later:

Dim value As Boolean
If Boolean.TryParse(yourString, value) = true Then 'Use value
else 'Handle a wrong text situation
End If

Boolean.TryParse ignore case. trUe or TRUE parsed ok

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like