I would do it like this:
String line = "unknownXoooXNOUNXccccccXunknown"; String regex = "Xo+X(.*?)Xc+X"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(line); if (m.find()) { String noun = m.group(1); }
(.*?) used to make internal NOUN reluctance. This protects us from the case when our final pattern appears again in an unknown part of the string.
EDIT
This works because (.*?) Defines a capture group. There, only one such group is defined in the template, so it gets index 1 (parameter m.group(1) ). These groups are indexed from left to right, starting with 1. If the template was defined as follows:
String regex = "(Xo+X)(.*?)(Xc+X)";
Then there would be three capture groups, such that
m.group(1); // yields "XoooX" m.group(2); // yields "NOUN" m.group(3); // yields "XccccccX"
There is group 0, but it matches the whole pattern and is equivalent to this
m.group();
For more information on what you can do with Matcher , including ways to get the start and end position of your template in the source string, see Matcher JavaDocs
source share