Re: regex problem



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
.



Relevant Pages

  • c#: inter-object event messaging (mediator pattern?)
    ... I then kind of gave up on trying to make it work with this pattern ... public static void Subscribe(string appEvent, AppEventHandler ...
    (microsoft.public.dotnet.languages.csharp)
  • Inter-object event messaging (Mediator Pattern?) (very long sorry)
    ... I then kind of gave up on trying to make it work with this pattern ... public static void Subscribe(string appEvent, AppEventHandler ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Briar bit me. Twice
    ... because he'd already done far more damage than Briar has done ... or the dog having resource guarding issues (he ... An unfair pattern, but a pattern of your own nonetheless. ... wouldn't snatch food out of a strange dog's mouth even if I didn't have ...
    (rec.pets.dogs.behavior)
  • Re: TSCC: Shoot Sarah, its the only way
    ... trying to destroy him I wonder? ... corpse also formed the same pattern. ... I'll tell you what the greatest thing about that episode was. ... The dog was later seen dead on the floor and I have my ...
    (uk.media.tv.misc)
  • Re: TSCC: Shoot Sarah, its the only way
    ... corpse also formed the same pattern. ... I'll tell you what the greatest thing about that episode was. ... The dog was later seen dead on the floor and I have my ... It does not wear me. ...
    (uk.media.tv.misc)