Using Regex OR operator to solve 2 conditions Using Regex OR operator to solve 2 conditions asp.net asp.net

Using Regex OR operator to solve 2 conditions


The | operator has a high precedence and in your original regex will get applied first. You should be combining the two regex's w/ grouping parentheses to make the precedence clear. As in:

"^(([A-Z]\d{8})|(\d{9}))$"


How about using ^[A-Z0-9]\d{8}$ ?


I think you want to group the conditions:

Regex.IsMatch(s, "^(([A-Z]\d{8})|(\d{9}))$")

The ^ and $ represent the beginning and end of the line, so you don't want them considered in the or condition. The parens allow you to be explicit about "everything in this paren" or "anything in this other paren"