您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

完整示例:

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)
    }
}

由于你要查找第一个数字,因此可以使用以下正则表达式:

^\D+(\d+).*

m.group(1)会返回你的第一个电话号码。请注意,带符号的数字可以包含减号:

^\D+(-?\d+).*
java 2022/1/1 18:20:52 有265人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶