File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes regular expression for not matching Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "regular expression for not matching" Watch "regular expression for not matching" New topic
Author

regular expression for not matching

Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 26496
    
  78

I'm not sure whether to post this in beginners or intermediate since it's either really easy or not. I guess I'll find out once it is answered.

How do you match everything but a given string? For example, suppose I want to match strings that don't contain "hello". So "hi", "test" and "moose" would match, but "hello world" and "hello" would not.

This is part of a larger reg exp so I can't just negate the result.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Alan Moore
Ranch Hand

Joined: May 06, 2004
Posts: 262
There are several ways to do that; none of them are as simple as they should be, and they all use negative lookahead. Here's one: <blockquote>code:
<pre name="code" class="core">str.matches("(?!.*hello).*")</pre>
</blockquote> Or, if you only want to exclude "hello" as a whole word: <blockquote>code:
<pre name="code" class="core">str.matches("(?!.*\\bhello\\b).*")</pre>
</blockquote>
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 26496
    
  78

Perfect. Thanks Alan. This definitely belongs in intermediate .

Now to merge this with the ugly reg exp it fits into...
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: regular expression for not matching
 
Similar Threads
Regex
Database searching
regex
Need help with regexp
Matching words except those in tags with regex