Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Regex Match Multiple Words

Tags:

java

regex

Lets say that you want to match a string with the following regex: ".when is (\w+)." - I am trying to get the event after 'when is'

I can get the event with matcher.group(index) but this doesnt work if the event is like Veteran's Day since it is two words. I am only able to get the first word after 'when is'

What regex should I use to get all of the words after 'when is'


Also, lets say I want to capture someones bday like

'when is * birthday

How do I capture all of the text between is and birthday with regex?

like image 796
user1414202 Avatar asked Dec 20 '22 14:12

user1414202


2 Answers

You could try this:

^when is (.*)$

This will find a string that starts with when is and capture everything else to the end of the line.

The regex will return one group. You can access it like so:

String line = "when is Veteran's Day.";
Pattern pattern = Pattern.compile("^when is (.*)$");
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
    System.out.println("group 1: " + matcher.group(1));
    System.out.println("group 2: " + matcher.group(2));
}

And the output should be:

group 1: when is Veteran's Day.
group 2: Veteran's Day.
like image 121
roydukkey Avatar answered Jan 07 '23 13:01

roydukkey


If you want to allow whitespace to be matched, you should explicitly allow whitespace.

([\w\s]+)

However, roydukkey's solution will work if you want to capture everything after when is.

like image 20
merlin2011 Avatar answered Jan 07 '23 11:01

merlin2011