创建正则表达式以使用java从字符串中提取4位数字 [英] Creating regex to extract 4 digit number from string using java

查看:236
本文介绍了创建正则表达式以使用java从字符串中提取4位数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我正在尝试构建一个正则表达式,使用java从给定字符串中提取4位数字。我通过以下方式尝试了它:

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 from string";
    Pattern pattern = Pattern.compile("^[0-9]+$");
    //Pattern pattern = Pattern.compile("^[0-90-90-90-9]+$");
    //Pattern pattern = Pattern.compile("^[\\d]+$");
    //Pattern pattern = Pattern.compile("^[\\d\\d\\d\\d]+$");

    Matcher matcher = pattern.matcher(mydata);
    String val = "";
    if (matcher.find()) {
        System.out.println(matcher.group(1));

        val = matcher.group(1);
    }

但它无法正常工作。这该怎么做。需要一些帮助。谢谢。

But it's not working properly. How to do this. Need some help. Thank you.

推荐答案

将您的模式更改为:

Pattern pattern = Pattern.compile("(\\d{4})");

\d 用于数字和 {} 中的数字是您想要的位数。

\d is for a digit and the number in {} is the number of digits you want to have.

这篇关于创建正则表达式以使用java从字符串中提取4位数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆