In the following code:
public static void main(String[] args) { List<String> allMatches = new ArrayList<String>(); Matcher m = Pattern.compile("\\d+\\D+\\d+").matcher("2abc3abc4abc5"); while (m.find()) { allMatches.add(m.group()); } String[] res = allMatches.toArray(new String[0]); System.out.println(Arrays.toString(res)); }
The result is:
[2abc3, 4abc5]
I'd like it to be
[2abc3, 3abc4, 4abc5]
How can it be achieved?
Make the matcher attempt to start its next scan from the latter \d+
.
Matcher m = Pattern.compile("\\d+\\D+(\\d+)").matcher("2abc3abc4abc5"); if (m.find()) { do { allMatches.add(m.group()); } while (m.find(m.start(1))); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With