Using Regular Expressions to Extract a Value in Java

前端 未结 13 1362
失恋的感觉
失恋的感觉 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:49

    Full example:

    private static final Pattern p = Pattern.compile("^([a-zA-Z]+)([0-9]+)(.*)");
    public static void main(String[] args) {
        // create matcher for pattern p and given string
        Matcher m = p.matcher("Testing123Testing");
    
        // if an occurrence if a pattern was found in a given string...
        if (m.find()) {
            // ...then you can use group() methods.
            System.out.println(m.group(0)); // whole matched expression
            System.out.println(m.group(1)); // first expression from round brackets (Testing)
            System.out.println(m.group(2)); // second one (123)
            System.out.println(m.group(3)); // third one (Testing)
        }
    }
    

    Since you're looking for the first number, you can use such regexp:

    ^\D+(\d+).*
    

    and m.group(1) will return you the first number. Note that signed numbers can contain a minus sign:

    ^\D+(-?\d+).*
    

提交回复
热议问题