Link to home
Start Free TrialLog in
Avatar of LiebertUser
LiebertUser

asked on

Do a logical AND in REGULAR EXPRESSIONS

I need a regular expression to return matches only IF a keyword appears in a string AND one or more match words also appear in the string.

Here is an example.  I want to return matches for the words "DOGS", "CATS", "GOLDFISH" but only if the word "PETS" is in the string  

For example, the sentence "CATS, DOGS AND GOLDFISH ARE POPULAR PETS" would return "CATS  DOGS GOLDFISH".

The sentence "DOGS, CATS AND GOLDFISH ARE TYPES OF ANIMALS" would not return anything because PETS is not in the string.

Is there a way to do this with a regular expression?  I'm new to regular expressions and would have never dreamed it would be so difficult.  I can match words no problem but I can't code the conditional AND to have it not show anything if a given word is not there.

This has drove me crazy all afternoon.  Thanks in advance for advice...

I will ultimately be using the expression from VB 2005 using the .net regex library.
Avatar of Patrick Matthews
Patrick Matthews
Flag of United States of America image

No need for regexp here as simple sql does it easily.

Use a where clause such as:

Where somecolumn like '%pets%' and (somecolumn like '%dogs%' or somecolumn like '%cats%' or somecolumn like '%goldfish%')
It's possible using a regex if the flavour of regular expression supports lookaheads, which .NET does. It's done like this:

(?=.*PETS)(DOGS|CATS|GOLDFISH)
(?=.*PETS)(DOGS|CATS|GOLDFISH)
matches the same strings as
(DOGS|CATS|GOLDFISH).*PETS
Perhaps you meant
(?=.*PETS).*(DOGS|CATS|GOLDFISH)
Thanks ozo
I'm as big a fan of RegExp as anyone, but I suspect relying on native SQL Server functionality will perform better in this instance :)

Turning on full text indexing and using the contains function may do even better:

http://www.developer.com/db/article.php/3446891/Understanding-SQL-Server-Full-Text-Indexing.htm
ASKER CERTIFIED SOLUTION
Avatar of SyfAldeen
SyfAldeen
Flag of Egypt image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of LiebertUser
LiebertUser

ASKER

Thanks SyfAldeen, TerryAtOpus and ozo.  Don't be sore at me because I accepted SyfAldeen's solution.  I was so stumped that all of the Regex solutions worked good for me but SyfAldeen's Regex did in fact catch the 3rd test string where the first two didn't.
I need to read more on Regular Expressions but this was one time I was so flustered because nothing I did worked.  I will learn so much more by dissecting your working example.  
P.S.  I do have a real production use for this regex that involves part#s etc, but instead of clouding the question with our data nomenclature I hoped kitties and dogs would make more sense.  Apperently it did!  THANKS AGAIN!