B"H I am unable to extract a consecutive set of numbers from within a (single line) string using ([0-9]+). However, surrounding it with match-all other does work (.*?[0-9].*). Can someone explain to me why ([0-9]+) is not working for this task. Here's my code:

public void testMethod(){
    Pattern pat = Pattern.compile("([0-9]+)");
    Matcher matcher = pat.matcher("red fox 11133434 red fox");
    Boolean matches = matcher.matches();
    Assert.assertTrue("find numbers within string", matches);
    Assert.assertEquals("11133434", matcher.group(1));

You are using a capturing group so this works as you expect: (You need to use find):

Pattern pat = Pattern.compile('([0-9]+)');
    Matcher matcher = pat.matcher('red fox 11133434 red fox');
    Boolean matches = matcher.find();

You will notice the debugs are true and 11133434

A good site to test out your regex and break it down it:




Thanks Eric for answering the question. Just for completeness I am sharing the definition difference between find and matches from the Java docs:

A matcher is created from a pattern by invoking the pattern's matcher method. Once created, a matcher can be used to perform three different kinds of match operations:

  • The matches method attempts to match the entire input sequence against the pattern.
  • The lookingAt method attempts to match the input sequence, starting at the beginning, against the pattern.
  • The find method scans the input sequence looking for the next subsequence that matches the pattern.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.