Java中用正则表达式判断,字符串是否全是数字

Java中用正则表达式判断,字符串是否全是数字

自己整理了几个正则表达式,不是很懂。。但能用。

package com.guo;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
    public static void main(String[] args) {

        System.out.println(isNum3("str324234"));
        System.out.println(isNum3("ew2345errw"));
        System.out.println(isNum3("43535334"));
        System.out.println(isNum3("34"));
        System.out.println(isNum3("3423_2313"));
        System.out.println(isNum3("12水56"));
        System.out.println(isNum3("-123456"));
        System.out.println(isNum3("123456"));

    }

  
    public static boolean isDigit1(String str) {
        if (str == null)
            return false;
        return str.matches("[0-9]{1,}");
    }

    public static boolean isDigit2(String strNum) {
        Pattern pattern = Pattern.compile("[0-9]{1,}");
        Matcher matcher = pattern.matcher(strNum);
        return matcher.matches();
    }

    public static boolean isNum1(String strNum) {
        //Pattern pattern = Pattern.compile("[0-9]*"); // 此方法只验证正数
        //Pattern pattern = Pattern.compile("-[0-9]*"); // 此方法只验证负数
        Pattern pattern = Pattern.compile("-?[0-9]*"); // 验证数字
        // Pattern pattern = Pattern.compile("-?[0-9]+?[0-9]+");(与上一行同效果)

        Matcher matcher = pattern.matcher(strNum);
        return matcher.matches();
    }

    public static boolean isNum2(String str){
        if (str == null)
            return false;
        return str.matches("[0-9]+");
    }

    public static boolean isNum3(String str) {
        if (str == null)
            return false;
        Pattern pattern = Pattern.compile("^-?\\d+(\\.\\d+)?$");
        return pattern.matcher(str).matches();
    }

    // 与isNum1效果相同
    public static boolean isNum4(String str) {
        Pattern pat = Pattern.compile("^-?[0-9]+$");
        Matcher mat = pat.matcher(str);
        if (mat.find()) {
            return true;
        } else {
            return false;
        }
    }

}

菜鸟教程的Java正则表达式

菜鸟教程的正则表达式教程

一篇挺棒的博文

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值