且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Java 中使用正则表达式提取值

更新时间:2021-12-02 23:11:21

完整示例:

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+).*

m.group(1) 将返回您的第一个数字.请注意,有符号数可以包含减号:

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

^D+(-?d+).*