Creating regex to extract 4 digit number from string using java

12,118

Solution 1

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.

Solution 2

If you want to end up with 0025,

String mydata = "get the 0025 data from string";
mydata = mydata.replaceAll("\\D", ""); // Replace all non-digits

Solution 3

Pattern pattern = Pattern.compile("\\b[0-9]+\\b");

This should do it for you.^$ will compare with the whole string.It will match string with only numbers.

Share:
12,118
nilkash
Author by

nilkash

Updated on June 11, 2022

Comments

  • nilkash
    nilkash almost 2 years

    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.

  • Sarz
    Sarz almost 9 years
    Try something like are you not sure about it?
  • Chop
    Chop almost 9 years
    Would it not be better to drop the parentheses and use group(0)? (micro-optimization, true, but when dealing with more complex patterns, it could come in handy)
  • JiriS
    JiriS almost 9 years
    Okay - corrected (The original question used as well expression "...I tried it in following ways:...")
  • Noor Hossain
    Noor Hossain about 4 years
    this is the best and easiest approach.