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

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

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest