![]() |
Regex to not match a string
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 -- Neil Aggarwal, (281)846-8957, www.JAMMConsulting.com Will your e-commerce site go offline if you have a DB server failure, fiber cut, flood, fire, or other disaster? If so, ask about our geographically redundant database system. |
Re: Regex to not match a string
Neil wrote:
> 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. -- Beware of bugs in the above code; I have only proved it correct, not tried it. -- Donald E. Knuth |
Re: Regex to not match a string
On Fri, 28 Aug 2009 17:59:31 -0700 (PDT), Neil
<neil@JAMMConsulting.com> wrote, quoted or indirectly quoted someone who said : >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) |
Re: Regex to not match a string
Joshua Cranmer <Pidgeot18@verizon.invalid> wrote:
>> 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. > (?!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. > -- > Beware of bugs ... heh, I read "Beware of the dogs ..." this time :-) |
| All times are GMT. The time now is 01:41 AM. |
Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.