Using Regular Expressions to Extract a Value in Java

前端 未结 13 1351
失恋的感觉
失恋的感觉 2020-11-22 13:08

I have several strings in the rough form:

[some text] [some number] [some more text]

I want to extract the text in [some number] using the

13条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 13:34

    Simple Solution

    // Regexplanation:
    // ^       beginning of line
    // \\D+    1+ non-digit characters
    // (\\d+)  1+ digit characters in a capture group
    // .*      0+ any character
    String regexStr = "^\\D+(\\d+).*";
    
    // Compile the regex String into a Pattern
    Pattern p = Pattern.compile(regexStr);
    
    // Create a matcher with the input String
    Matcher m = p.matcher(inputStr);
    
    // If we find a match
    if (m.find()) {
        // Get the String from the first capture group
        String someDigits = m.group(1);
        // ...do something with someDigits
    }
    

    Solution in a Util Class

    public class MyUtil {
        private static Pattern pattern = Pattern.compile("^\\D+(\\d+).*");
        private static Matcher matcher = pattern.matcher("");
    
        // Assumptions: inputStr is a non-null String
        public static String extractFirstNumber(String inputStr){
            // Reset the matcher with a new input String
            matcher.reset(inputStr);
    
            // Check if there's a match
            if(matcher.find()){
                // Return the number (in the first capture group)
                return matcher.group(1);
            }else{
                // Return some default value, if there is no match
                return null;
            }
        }
    }
    
    ...
    
    // Use the util function and print out the result
    String firstNum = MyUtil.extractFirstNumber("Testing4234Things");
    System.out.println(firstNum);
    

提交回复
热议问题