简体   繁体   中英

How to use Pattern.matches with regex to filter unwanted characters in a string

I am working on a program for a class that requires us to hand an input string to the Integer.parseInt function. Before I hand the string off I want to make sure that it doesn't contain any non-numeric values. I created this while function with Pattern.matches to attempt this. This is the code:

while((Pattern.matches("[^0-9]+",inputGuess))||(inputGuess.equals(""))) //Filter non-numeric values and empty strings.
                {
                    JOptionPane.showMessageDialog(null, "That is not a valid guess.\nPlease try again.");
                    inputGuess=(JOptionPane.showInputDialog(null, "Enter your guess.\nPlease enter a numeric value between 1 and 12."));
                }

Whenever I enter any letter, punctuation, or "special characters" the while statement takes affect as it should. But, whenever I introduce any combination of letters, punctuation, or "special characters" and a number the program crashes and burns. My question is: Is there a way to use Pattern.matches with regex that will allow me to prevent any combination of numbers and letters,punctuation or "special characters" from being handed to the Integer.parseInt, yet still allow just numbers to be handed off to the Integer.parseInt.

Try this:

!Pattern.matches("[0-9]+",inputGuess)

Or more succinctly:

!Pattern.matches("\\d+",inputGuess)

Using + obviates the need to check for the empty string too.

Note that it is still possible for Integer.parseInt to fail with out-of-bounds.

To prevent that, you can do

!Pattern.matches("\\d{1,9}",inputGuess)

though this precludes some large valid integer values (anything one billion or more).

Honestly, I would just use try-catch with Integer.parseInt and check its sign if necessary.

Your program does not work because Pattern.matches requires the whole string to match the pattern. Instead, you want to display an error even if a single substring of your string matches your pattern.

This can be done by means of the Matcher class

public static void main(String[] args) {
    Pattern p = Pattern.compile("[^\\d]");

    String inputGuess = JOptionPane.showInputDialog(null, "Enter your guess.\nPlease enter a numeric value between 1 and 12.");

    while(inputGuess.equals("") || p.matcher(inputGuess).find()) //Filter non-numeric values and empty strings.
    {
        JOptionPane.showMessageDialog(null, "That is not a valid guess.\nPlease try again.");
        inputGuess=(JOptionPane.showInputDialog(null, "Enter your guess.\nPlease enter a numeric value between 1 and 12."));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM