Java regex matches to arraylist

Converting my comment to answer so that solution is easy to find for future visitors.

You may use a simpler regex without any capture group:

[^ ]+#\\d{4}

Which matches 1+ of a non-space characters before # and then 4 digits.


final String line = "There were bear#67 with dog#1323 and cat#5475 in the forest";

final Pattern r = Pattern.compile("[^ ]+#\\d{4}");    
Matcher m = r.matcher(line);

List<String> arr = new ArrayList<>();

while (m.find( )) {

//=> [dog#1323, cat#5475]

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top