I have the strings:
String myString1 = "22223 2342 1 98 333 3 665"
String myString2 = "22323 3 222 34 33 1 98"
I want to only extract the value that has 1 digit, then a space, then only two digits.
private static final Pattern p3DigitsGap = Pattern.compile(".*\\b\\d\\s\\d{2}\\b.*");
In both of the above strings, I’m looking to extract “1 98” I cannot just split by whitespace either side in case the pattern is at the end of the string.
Matcher matcher = p3DigitsGap.matcher(myString1);
if (matcher.find()) {
Log.i("Matcher found");
while (matcher.find() == true) {
Log.i("Matcher is true");
String extract = matcher.group(1);
Log.d("extract: " + extract);
}
}
The String extract is never populated and throws an out of bounds exception if I remove the while loop. I added in the while loop and matcher.find() doesn’t equal true.
I tried swapping my pattern to:
Pattern p3DigitsGap = Pattern.compile("[^0-9a-z]\\d\\s\\d{2}[^0-9a-z]");
I thought that the use of the .*\\b may be causing the issue, but I get the same result.
Please can someone help me understand where I’m going wrong.
Thanks in advance.
ANSWER EDIT: I marked the answer by Reimeus correct, as it works by using groups with the above regex. Please also see the answer by Tim Pietzcker for an alternative solution that improves on my original regex.
Better to use groups when matching, so you could use: