如何检查一个字符串只包含数字?

阅读量: 528 编辑

如何检查一个字符串只包含数字?

使用正则表达式进行判断

package com.qc.java67;

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

public class RegularExpressionDemo {

    //怎么检查一个字符串只包含数字?
    public static void main(String args[]) {

        // Regular expression pattern to test input
        String regex = "(.)*(\\d)(.)*";
        Pattern pattern = Pattern.compile(regex);

        Scanner reader = new Scanner(System.in);
        String input = "TEST";

        System.out.println("Please enter input, must contain at-least one digit");
        while (!input.equalsIgnoreCase("EXIT")) {

            input = reader.nextLine();
            // Pattern pattern = Pattern.compile(regex);// Don't do this, creating Pattern is expensive

            Matcher matcher = pattern.matcher(input);
            boolean isMatched = matcher.matches();
            if (isMatched) {
                System.out.println("PASS");

            } else {
                System.out.println("FAIL, Incorrect input");

            }
        }
    }


}

苏ICP备13052010号-3
©2022 南京匠成信息科技有限公司