Re: regex problem
- From: jamil@xxxxxxxxxxx
- Date: Fri, 29 Aug 2008 22:16:24 -0400
On Sat, 30 Aug 2008 03:29:26 +0200, Claudio Nieder
<private@xxxxxxxxxx> wrote:
Hello, Claudio.
Hi,
The regular expression to do what you requested is simple borderline
trivial. There really is nothing complex about it, unless you are not
Well, in the exaples which have been posted here we had just seen how to
have one regular expression not match the word dog. But not yet, how to
write one which would match if the sentnece contains cat unless it also
contains dog.
To get the result
"I have no pets" ==> false
"I have a cat as pet" ==> true
"I have a dog at home" ==> false
"I got a cat and a dog" ==> false
"My dog hates my cat" ==> false
....
How would a single regular expression for this look like?
claudio
It took me less than ten seconds to construct the regular expression:
"^(?!.*\\bdog\\b.*$).*\\bcat\\b.*$"
This time I accounted for full word matches on the first try.
It took a little more time to actually write the code:
import java.util.regex.*;
public class Output {
private static String pattern;
public static void main(String[] args) {
setPattern("^(?!.*\\bdog\\b.*$).*\\bcat\\b.*$");
regexMatch("I have no pets");
regexMatch("I have a cat as pet");
regexMatch("I have a dog at home");
regexMatch("I got a cat and a dog");
regexMatch("My dog hates my cat");
}
private static void regexMatch (String textIn) {
Matcher m1 = Pattern.compile(pattern).matcher(textIn);
System.out.println(m1.matches());
}
public static void setPattern(String patternIn) {
pattern = patternIn;
}
}
----------------
false
true
false
false
false
.
- References:
- Re: regex problem
- From: Claudio Nieder
- Re: regex problem
- From: km_jr_usenet
- Re: regex problem
- From: Claudio Nieder
- Re: regex problem
- Prev by Date: Re: how to parse a xml document which has a combination of XML XQuery and XPath
- Next by Date: Re: exceptions: checked or unchecked?
- Previous by thread: Re: regex problem
- Next by thread: maths
- Index(es):
Relevant Pages
|