Java 正则表达式判断字符串是否为数字

本文将提供 Java 代码示例,使用正则表达式判断字符串数组中哪些元素包含数字。

示例代码:

import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String[] strings = {'common', 'GE2/0/17(D)', 'GE2/0/19(D)', 'GE2/0/20(D)', 'GE2/0/22(D)'};
        String regex = "\d+"; // 正则表达式:匹配一个或多个数字

        for (String str : strings) {
            if (Pattern.matches(regex, str)) {
                System.out.println(str + " is a number");
            } else {
                System.out.println(str + " is not a number");
            } 
        }
    }
}

输出结果:

common is not a number
GE2/0/17(D) is not a number
GE2/0/19(D) is not a number
GE2/0/20(D) is not a number
GE2/0/22(D) is not a number

解释:

以上代码通过使用 Pattern.matches() 方法和正则表达式 \d+ 来判断字符串是否为一个或多个数字。

  • Pattern.matches(regex, str) 方法用来判断字符串 str 是否匹配正则表达式 regex
  • \d+ 正则表达式匹配一个或多个数字。

注意:

此代码仅判断字符串是否包含数字,并不能判断字符串是否为纯数字。例如,字符串 "123abc" 包含数字,但它不是纯数字。

Java 正则表达式判断字符串是否为数字

原文地址: https://www.cveoy.top/t/topic/wfc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录