Home arrow static arrow Java Programming [Archive] - Regex Question
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - Regex Question
This topic has 1 reply on 1 page.

Registered: 9/25/01
Regex Question  
Jul 23, 2004 4:06 AM


Can any one tell how to create a Pattern for a String which should not contain a specific word ?

For example,
In the String "quick brown fox",
the string to be matched for a pattern can contain the words "quick" and "fox" but should not contain the word "brown"

Pattern.matches(pattern,"quick fox"); -----> should return true
Pattern.matches(pattern, "quick brown fox"); ----> should return false

What will be the Pattern.?


Registered: 9/26/00
Re: Regex Question  
Jul 23, 2004 6:28 AM (reply 1 of 1)

Well, the simplest way would be to use a regex that looks for the word "brown" and negate the result of matches(), but I assume you want to use the regex to do all the work. Here's one way:
  String regex = "(?i:\\W++|b(?!rown\\b)\\w*+|\\w++)+";

The outer parentheses, "(?i:...)", create a non-capturing group within which all matching will be case-insensitive. With each iteration, the group will match: 1) a sequence of non-word characters; 2) a sequence of word characters beginning with the letter 'b', unless it's the word "brown"; or 3) any other sequence of word characters.

This regex will fail to match if the input contains the whole word "brown", but not if it contains longer words like "brownie". Hyphentated words like "brown-noser" will cause it to fail, which would probably be incorrect; if that's a problem, another alternative can be added to deal with it.
This topic has 1 reply on 1 page.