验证字符串只包含java中的某些字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20038426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:32:49  来源:igfitidea点击:

Validate a string contains only certain characters in java

javavalidation

提问by Neonjoe

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, +, -, *, /, %

我正在苦苦挣扎的是,对于用户输入,我需要验证它是否仅包含以下内容:()、0-9、+、-、*、/、%

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

每个字符将由一个空格分隔,因此这里是一个潜在的有效输入:

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

( 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.

我创建了一个 InvalidCharacterException,如果用户字符串包含除这些字符以外的任何内容,我希望抛出该异常。

Here is what an invalid input would look like:

这是无效输入的样子:

3 - 5 ^ 5

3 - 5 ^ 5

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

^ 将是一个无效字符,然后我会抛出新的 InvalidCharacterException 并要求一个新的输入。

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.

Infix 是我的用户输入的变量名作为 StringBuffer。

采纳答案by David SN

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.

findInLine 方法返回一个字符串,其中包含与正则表达式匹配的字符,正则表达式会查找验证中无效的任何字符。findInLine 仅在字符串中存在任何无效字符时返回非空字符串。

回答by Elliott Frisch

I would suggest you use a Scanner(for an example) and then loop over each character (in each token) and throw your Exception if your criteria are met (e.g. look at Character.isDigit) or just write your own method to test against acceptable characters (e.g. is char is contained in"()0123456789+-*/%").

我建议您使用Scanner例如)然后遍历每个字符(在每个标记中)并在满足您的条件时抛出您的异常(例如查看Character.isDigit)或者只编写您自己的方法来测试可接受的字符(例如字符包含在“()0123456789+-*/%”中)。

回答by Hoodlum

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

在您的代码中,这可能更好,因为它做同样的事情。顺便说一句,它可能应该是 i < infix.length() 而不是 <=

 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*/

 }