简体   繁体   中英

Validate a string contains only certain characters in java

Ok, what I am trying to do is take a user input in infix notation and translate it to postfix and then evaluate it. I have that already completed.

What I am struggling with, is for the user input I need to validate that it only contains the following: (), 0-9, +, -, *, /, %

Each character will be separated by a space, so here is a potential valid input:

( 3 + 4 ) * 5 / ( 6 - 7 )

I have created an InvalidCharacterException that I wish to throw if the user string contains anything other than those characters.

Here is what an invalid input would look like:

3 - 5 ^ 5

The ^ would be an invalid character and then I would throw new InvalidCharacterException and ask for a new input.

I will also say I have looked at a ton of regex samples, and to be honest I don't understand what they're doing.

EDIT:

Ok, this is what I ended up implementing because I don't really understand anything else. Any advice on a simpler way?

    for(int i = 0; i <= infix.length(); i++){
        if(infix.charAt(i) ==  '(' || infix.charAt(i) == ')' || infix.charAt(i) =='+' 
                || infix.charAt(i) =='-' ||infix.charAt(i) == '*' ||infix.charAt(i) == '/'
                ||infix.charAt(i) == '%' ||infix.charAt(i) ==' ' ||infix.charAt(i) == '0' 
                ||infix.charAt(i) == '1' || infix.charAt(i) =='2' || infix.charAt(i) =='3' 
                ||infix.charAt(i) == '4' ||infix.charAt(i) == '5' ||infix.charAt(i) == '6' 
                ||infix.charAt(i) == '7' || infix.charAt(i) =='8' ||infix.charAt(i) == '9'){

        }else{
            throw new InvalidCharacterException(infix.charAt(i));
        }

    }

Infix is the variable name of my user input as a StringBuffer.

You can use a Scanner to validate your string:

    Scanner scanner = new Scanner(string);        
    String validationResult = scanner.findInLine("[^0-9()+\\-*\\/%]+");
    if (validationResult != null) {
        // Invalid character found.
        throw new InvalidCharacterException("Invalid character: " + validationResult);
    }

The findInLine method returns a String with the characters that match the regex and the regex looks for any character not valid in your validation. The findInLine only returns a non null String when there are any invalid characters in the String.

我建议您使用Scanner例如 ),然后遍历每个字符(在每个令牌中),如果满足条件(例如,查看Character.isDigit ),则抛出Exception,或者只是编写自己的方法来测试可接受性字符(例如,char是否包含在“()0123456789 +-* /%”中)。

In your code this is probably better because it does the same thing. Btw it probably should be i < infix.length() not <=

 for(int i = 0; i < infix.length(); i++){
        char x = infix.charAt(i);
        if(!(Character.isDigit(x) || x == '/' || x == '*' ||
           x == '+'|| x== '-' || x=='%' || x == '\n'))
            throw new InvalidCharacterException(x);


        /* what you want to do if valid*/

 }

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