RegEx Question

  • Thread starter Thread starter Scott Turner
  • Start date Start date
S

Scott Turner

I need help creating a regular expression which will match the following:

"foo" anywhere in the text
Also the text should contain either "bar" or "bar1"

Following are some examples of text which should return a match:

xxxx foo xxxx xxx bar xxxx
xxxx foo xxxx xxx bar1 xxxx
xxxx bar xxxxxxx foo xxxxx xxxx
xxxx bar1 xxxxxxx foo xxxxx xxxx
xxxx bar1 xxxx bar xxx foo xxxxx xxxx
xxx foo xxxxx xxxx xxxx bar1 xxxx bar

Thanks,
Scott
 
Scott:

Do you want to match the whole line, just the foo and the bar or bar1, all
the xxx's between them? And what to do if bar and bar1 appear in the same
line (one foo, one bar and one bar1?).
 
If you want to match the "foo" part only, use this:
((?<=(bar|bar1).*)foo|foo(?=.*(bar|bar1)))

If you want to match the whole line, use this:
..*(bar|bar1).*foo.*|.*foo.*(bar|bar1).*

If you don't really need the matched text and just need to know if there is
a match, use the IsMatch function with either of these.

Also, I am assuming that you really aren't going to be looking for the
literals "bar" or "bar1". If for some reason you were, then you would only
need to look for "bar" since it is contained within "bar1".

Brian Davis
www.knotdotnet.com
 
Thanks Brian!

I am using the static IsMatch method, and had originally created a
RegEx much like the ones you suggested. However, when looping through
articles and testing for matches, it is much slower than what I need.

If I can't find a faster way to test for a match, I will just have to
re-architect things.

Scott
 
Back
Top