I am trying to match two or more words in a string. The string is My/word example/word I want to extract My example. what I did so far is:
String test = "My/word example/word";
Pattern pattern = Pattern.compile("((.*)\\/word){2,}");
Matcher match = pattern.matcher(test);
if (match.find()) {
System.out.println(match.group(1));
}
But it prints example/word only, any ideas?
If you have any repetition with a capturing group, it will only capture the final match of that group. Your best option here would be to simplify the regex to only match one word, and then use
match.find()repeatedly until you do not find a match:It shouldn’t be difficult to add some logic here to only print if you find two or more matches.
Also note that I modified your regex a bit, forward slashes don’t need to be escaped and I replace
.*with\w+which should be better because you won’t greedily match up to the very last/word.