How to make regex alternation return first match?

Hi,

I have the following string:

"i am a man and i have a cat and a dog and a bird"

and I wish to extract the part of the sentence from "man" up to the first occurence of "dog" or "cat". So I wish the extracted sentence to be

"and i have a"

or alternatively

"man and i have a cat"

I would guess the regular expression "man.*(cat|dog)" should do it, but that seems to always return the sentence up to the last occurrence of dog and cat, when I want the first occurrence. So "man.*(cat|dog)" returns (when using find() and group()):

"man and i have a cat and a dog"

Anyone have any ideas how I can return the sentence from (preferably excluding) man and to (preferably excluding) the first occurrence of cat or dog?

Thanks!

Message was edited by:

MagnusGJ

Message was edited by:

MagnusGJ

[882 byte] By [MagnusGJa] at [2007-11-27 11:48:02]
# 1

Take your pick -

// One possibility

String target = "i am a man and i have a cat and a dog and a bird";

String result = target.replaceFirst(".*?man (.*?)( cat| dog).*", "$1");

System.out.println(result);

// and another

Matcher m = Pattern.compile("man (.*?) (cat|dog)").matcher(target);

if (m.find())

{

System.out.println(m.group(1));

}

sabre150a at 2007-7-29 18:16:39 > top of Java-index,Java Essentials,Java Programming...
# 2

That works perfectly, thanks sabre150

MagnusGJa at 2007-7-29 18:16:39 > top of Java-index,Java Essentials,Java Programming...