Java如何提取一个字符串中所有数字字符呢?
下文笔者讲述使用java代码提取字符串中所有数字字符的方法分享,如下所示
提取字符串中数字字符的实现思路
1.定义一个正则表达式 2.使用String类中matches()方法 或 Pattern类中的matcher()方法匹配例
String str = "abc123def456ghi789"; // 使用matches()方法 if (str.matches(".*\\d+.*")) { String nums = str.replaceAll("\\D+", ""); System.out.println("数字字符串为:" + nums); } // 使用matcher()方法 Pattern pattern = Pattern.compile("\\d+"); Matcher matcher = pattern.matcher(str); while (matcher.find()) { System.out.println("数字字符串为:" + matcher.group()); }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。