I’m trying to get the pipe (OR) to work. I have this regular expression with these tests:
string output = "test: {0} matches";
string test = "AND [Field] =";
Regex r = new Regex(@"AND|OR\s[?\w+]?\s?=");
if (r.IsMatch(test))
Console.WriteLine(string.Format(output, test));
test = "OR [Field] =";
if (r.IsMatch(test))
Console.WriteLine(string.Format(output, test));
The first match passes but the second fails. I can’t figure out why the | between the AND and OR does not act like an OR statement. I’ve tried putting parenthesis around the AND|OR but then both test fails.
Can anyone help me with the OR “|” statement please?
Within regex, alternation (
|) has lower precedence than sequence. Your regex pattern is interpreted as “ANDor (ORfollowed by\s[?\w+]?\s?=)” (note the parenthesis I added to denote precedence).To achieve what you want, you’ll need to parenthesize your
AND|ORpart, as well as escape your[and]characters.Furthermore, you probably do not want to allow an
[without a](or vice versa); either both should be present, or neither: