Java – Creating regex to extract 4 digit number from string using java

javaregexstringsubstring

Hi I am trying to build one regex to extract 4 digit number from given string using java. I tried it in following ways:

String mydata = "get the 0025 data from string";
    Pattern pattern = Pattern.compile("^[0-9]+$");
    //Pattern pattern = Pattern.compile("^[0-90-90-90-9]+$");
    //Pattern pattern = Pattern.compile("^[\\d]+$");
    //Pattern pattern = Pattern.compile("^[\\d\\d\\d\\d]+$");

    Matcher matcher = pattern.matcher(mydata);
    String val = "";
    if (matcher.find()) {
        System.out.println(matcher.group(1));

        val = matcher.group(1);
    }

But it's not working properly. How to do this. Need some help. Thank you.

Best Solution

Change you pattern to:

Pattern pattern = Pattern.compile("(\\d{4})");

\d is for a digit and the number in {} is the number of digits you want to have.