tags:

views:

61

answers:

2

Sample input: Did xxx xxx xxx (could be any number of words) live or die?

For example:

 Did   Michael      Jackson  live or     die     ?

I want to capture: Michael Jackson, live, die. The sentence can have any number of spaces between words.

How do I do it?

+1  A: 
Did\\s+(.+)\\s+(\\S+)\\s+or\\s+(\\S+)\\s*\\?

or am I missing something?

EDIT: changed single backslashes to double backslashes

mobrule
Nope. doesn't work.
Saobi
+1  A: 

Something like this would work. You will need to take the first group, Michael Jackson, and split it by the space character.

Pattern regex = Pattern.compile("^Did (.+)\s+(\w+)\s+or\s+(\w+)$", 
                                  Pattern.CASE_INSENSITIVE | 
                                  Pattern.UNICODE_CASE);
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) 
{
  String []person = regexMatcher.group(0).split(" ");
  String action1 = regexMatcher.group(1);
  String action2 = regexMatcher.group(2);
}
David Andres
What does split(" ") do?
Saobi
In this example, the text "Michael Jackson" will be split by a single space character. The end result will be a string array whose elements are "Michael" and "Jackson"
David Andres
Yes but your matcher will fail if i have multiple spaces between any word i think, or it'll capture "Michael Jackson live" instead of "Michael Jackson"
Saobi
I've adjusted the pattern so that multiple whitespace between words won't keep you from a match. I don't think it will capture "Michael Jackson live," if only because the pattern explicitly matches the word before the " or " separately.
David Andres
This works, thanks!!!!
Saobi