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

Java uses regular rules to determine whether it is a number

尚
Original
2019-12-28 09:27:514579browse

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

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

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

Pattern.matches(regex, str)

语法

public boolean matches(String regex)

参数: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!

Statement:
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