Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 478
  • Last Modified:

Regular expression match words - ignores OR

Hi All,

In C# I have the following variable that tests for the following matches... ' not ',' and ',' or '.

This seems to work fine when locating matches for ' not ' and ' and ' but it doesn't work when locating the keyword ' or '.

Can anyone see what I am doing wrong?

Match matchBoolOperators = Regex.Match(strSearchTerm.ToLower(), @"[ not ][ and ][ or ]");

Open in new window


Many thanks,

Rich
0
rito1
Asked:
rito1
  • 2
  • 2
2 Solutions
 
MichaelStaszewskiCommented:
Try using this as your regex instead.

(\s)(not|and|or)(\s)

Open in new window

0
 
rito1Author Commented:
Thanks MichaelStaszewski,

That didn't seem to work in my C#... I am starting to understand there their a different implementation of regexp for different languages... this seemed to work fine:

\bAND\b|\bNOT\b|\bOR\b

Open in new window

0
 
käµfm³d 👽Commented:
Can anyone see what I am doing wrong?
MichaelStaszewski's suggestion is the way to go. I'd like to add why.

You are using character classes in your regex. A character class works like a logical OR in regex. The caveat is that it works as an OR against the literal characters contained within it. In your case, what your pattern means is:

[ not ]  - Either a space, a "n", an "o", or a "t" (space is used twice, but as far as character classes go, repeated characters are treated as if they occurred only once)
[ and ]  - Either a space, an "a", a "n", or a "d" (space, see above)
[ or ]   - Either a space, an "o", or a "r" (space, see above

Open in new window


The effect of your pattern is that any of the following (and more) would match:

nar
nao
ndo
nnr
...
0
 
MichaelStaszewskiCommented:
I'm not a C# guy and use PCRE mostly. There are differences between regex engines. That's good you found a solution.
0
 
käµfm³d 👽Commented:
There's a nice comparison of features between the two (and others) on this page:  http://www.regular-expressions.info/refflavors.html
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now