Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regex - Get all words before substring in String

I have a string which contains a sentence and I want to split it in half, based on a word. I have the regex (\\w+) word which I thought would get me all the words before "word" + "word" itself, then I could just remove the last four chars.

However this doesn't seem to work.. any ideas what I've done wrong?

Thanks.

like image 468
crazyfool Avatar asked May 02 '12 19:05

crazyfool


1 Answers

This seems to work:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
    public static void main(String[] args) {
        Pattern p = Pattern.compile("([\\w\\s]+) word");
        Matcher m = p.matcher("Could you test a phrase with some word");
        while (m.find()) {
            System.err.println(m.group(1));
            System.err.println(m.group());
        }
    }
}
like image 113
Guillaume Polet Avatar answered Sep 21 '22 23:09

Guillaume Polet