Creating regex to extract 4 digit number from string using java

前端 未结 7 758
余生分开走
余生分开走 2021-01-20 22:26

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 f         


        
相关标签:
7条回答
  • 2021-01-20 22:53
    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.

    0 讨论(0)
  • 2021-01-20 22:53

    You can go with \d{4} or [0-9]{4} but note that by specifying the ^ at the beginning of regex and $ at the end you're limiting yourself to strings that contain only 4 digits.

    My recomendation: Learn some regex basics.

    0 讨论(0)
  • 2021-01-20 23:00

    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.

    0 讨论(0)
  • 2021-01-20 23:02

    If you want to match any number of digits then use pattern like the following:

    ^\D*(\d+)\D*$
    

    And for exactly 4 digits go for

    ^\D*(\d{4})\D*$
    
    0 讨论(0)
  • 2021-01-20 23:04

    If you want to end up with 0025,

    String mydata = "get the 0025 data from string";
    mydata = mydata.replaceAll("\\D", ""); // Replace all non-digits
    
    0 讨论(0)
  • 2021-01-20 23:05

    Remove the anchors.. put paranthesis if you want them in group 1:

    Pattern pattern = Pattern.compile("([0-9]+)");   //"[0-9]{4}" for 4 digit number
    

    And extract out matcher.group(1)

    0 讨论(0)
提交回复
热议问题