温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java用正则表达式判断字符串是否为数字的方法

发布时间:2020-06-10 10:59:56 来源:亿速云 阅读:814 作者:Leah 栏目:编程语言

这篇文章运用了实例代码展示java用正则表达式判断字符串是否为数字的方法,代码非常详细,可供感兴趣的小伙伴们参考借鉴,希望对大家有所帮助。

package com.yinxin.util;
 
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class Test {
	 /**
     * 判断一个字符串是否是数字。
     * 
     * @param string
     * @return
     */
    public static boolean isNumber(String string) {
        if (string == null)
            return false;
        Pattern pattern = Pattern.compile("^-?\\d+(\\.\\d+)?$");
        return pattern.matcher(string).matches();
    }
 
    private static void isNumberTest() {
        System.out.println(isNumber("580"));
        System.out.println(isNumber("5234254125424584"));
        System.out.println(isNumber("dfg15s4df5sd1fds"));
    }
 
    public static void main(String[] args) {
        isNumberTest();
    }
 
}

matches() 方法用于检测字符串是否匹配给定的正则表达式。

调用此方法的 str.matches(regex) 形式与以下表达式产生的结果完全相同:

Pattern.matches(regex, str)

语法

public boolean matches(String regex)

参数:regex -- 匹配字符串的正则表达式。

返回值:在字符串匹配给定的正则表达式时,返回 true。

以上就是java用正则表达式判断字符串是否为数字的方法,看完之后是否有所收获呢?如果想了解更多相关内容,欢迎关注亿速云行业资讯!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI