Regex to not match a string

N

Neil

Hello:

I have come up with a scenario where I need to form a regex that does
not match
either of two strings.

For example, I want the regex to match anything besides cat and dog,
horse
should yield a match, pig should yield a match, etc.

I tried this:
[^(cat|dog)]

but that did not work.

Any ideas?

Thanks,
Neil
 
J

Joshua Cranmer

Neil said:
Hello:

I have come up with a scenario where I need to form a regex that does
not match
either of two strings.

For example, I want the regex to match anything besides cat and dog,
horse
should yield a match, pig should yield a match, etc.

I tried this:
[^(cat|dog)]

but that did not work.

Any ideas?

(?!cat|dog) should work

The (?!) construct means a negative lookahead: it matches iff the regex
in the group does not match.
 
R

Roedy Green

Hello:

I have come up with a scenario where I need to form a regex that does
not match
either of two strings.

One way out is to write a regex to find either string then invert the
boolean result of matches
--
Roedy Green Canadian Mind Products
http://mindprod.com

"Any one who considers arithmetical methods of producing random digits is, of course, in a state of sin. For, as has been pointed out several times, there is no such thing as a random number — there are only methods to produce random numbers, and a strict arithmetic procedure of course is not such a method."
~ John von Neumann (born: 1903-12-28 died: 1957-02-08 at age: 53)
 
A

Andreas Leitgeb

Joshua Cranmer said:
(?!cat|dog) should work The (?!) construct means a negative lookahead...

There's also a way to construct "conventional" regular expressions, as long
as you can anchor the starting point of the not-occurrance of these words:
e.g.:
^([^cd]|c[^a]|d[^o]|ca[^t]|do[^g])

It quickly becomes messy as the not-to-occurrants become longer, and also
messier (but not so much), if you e.g. still want the catfish to pass the re.

heh, I read "Beware of the dogs ..." this time :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top