Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to "boolean NOT" in regex?  RSS feed

 
Ben Ethridge
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, everyone.

Been working in regex using the Pattern and Matcher classes, and most things are understandable.

One thing I can't figure out how to do, reading books, online and tinkering with it:

How do you do the "boolean NOT" in regex?

I think I understand the [^a] to "not" a single char, but how would you do something equivalent to this in java:

public static void main(String[] args) {
String matchPattern = "<title>";
String source = "This has a <title> in it, so reject the string";
if (source.contains(matchPattern)){
System.out.println("Even if other parts of the pattern match, make Matcher.matches() return false");
}
}


Ben
 
Ben Ethridge
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To answer part of my own question, one good hint is here:

http://regexadvice.com/blogs/justin_rogers/archive/2004/08/06/335.aspx

Ben
 
Alan Moore
Ranch Hand
Posts: 262
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So you want matches() to return false if something matching the regex is present? For that you need a negative lookahead:If you also need to positively match something, replace the second ".*" with the appropriate expression. Note that, if your text contains any line-separator characters, you'll also need to set the DOTALL flag, which you can do with an inline modifier:
 
Ben Ethridge
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, that will do it, I think.

Thanks, Alan.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!