views:

70

answers:

2

Hi,

I'm trying to write a regex which should be able to identify boolean expressions.

I need to avoid cases like IF(AND AND AND). The name of the variable shouldn't be one of the following operators (OR;AND;XOR).

I tried to use [^(OR)] but this wasn't helpful. My Regex looks like this:

(?:<Name> [A-Za-z0-9])

Is there any chance to write a Regex which could find a string like OR and then don't match it?

Thanks for your help.

Orri

+2  A: 

Try a negative lookahead:

(?<Name>\b(?!(?:and|x?or)\b)[A-Za-z0-9]+)

This assumes you're trying to match a single literal, like "IF(this AND this)". The regex checks before taking letters, if all it sees is "and" "or" or "xor", it fails.

Also, make sure you have the right RegexOptions set - you probably want IgnoreCase on, and unless you have IgnorePatternWhitespace the space in your original pattern might fail a match, there is no space in if(var1, for example.

Kobi
I tried to keep it as simple as possible
@user359446 - I'm not sure what that means `:|`
Kobi
I will try your solution thx The regex shouldn´t match if there is any of the boolean expressions
It needs to be `(?<name>..)`, not `(?:<name>...)`. That was already wrong in @user359446's question.
Tim Pietzcker
*doh It is right in my code but no here :)
@Tim - Thanks, fixed. I tested the regex, but not in .Net, so I omitted that part. Thanks.
Kobi
A: 

Hi, thx u Kobi, i tried your solution and it works fine. Is there any other ways to do stuff like this may one for dummies. I want to write readable code

a). use comments for follow-ups on SO, b). use comments in your code to clarify intent. Regex is what it is, you can't make it more or less readable.
annakata