Home > Java > JavaBase > Java uses regular rules to determine whether it is a number

Java uses regular rules to determine whether it is a number

Release: 2019-12-28 09:27:51
Original
4622 people have browsed it

Java uses regular rules to determine whether it is a number

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();
    }
 
}
Copy after login

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

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

Pattern.matches(regex, str)
Copy after login

语法

public boolean matches(String regex)
Copy after login

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

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

更多java知识请关注java基础教程栏目。

The above is the detailed content of Java uses regular rules to determine whether it is a number. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template