The snippet below should return and store matches in the ArrayList but for some reason, I get only the last match, that is 23; I would expect 256 and 23 of course. Could you tell me what I'm doing wrong? Thanks in advance.
public static void main(String[] args){ String target = "nawaK256he23llo"; String regexNb = "[0-9]+"; Pattern patternNb = Pattern.compile(regexNb); Matcher mNb = patternNb.matcher(target); List<String> allMatchesNb = new ArrayList<String>(); while (mNb.find()) { System.out.println("mNb matched : " + mNb.find()); allMatchesNb.add(mNb.group()); for (String nb : allMatchesNb) { System.out.println("content of ArrayList :" + nb); } } } Output is the following :
content of ArrayList : 23
find()twice at each iteration, once inwhileand once inprintln. Get rid of the second call .