简体   繁体   English

验证字符串仅包含Java中的某些字符

[英]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, +, -, *, /, % 我正在努力的是针对用户输入,我需要验证它仅包含以下内容:(),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。

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. findInLine方法返回一个字符串,该字符串具有与正则表达式匹配的字符,并且正则表达式查找在验证中无效的任何字符。 The findInLine only returns a non null String when there are any invalid characters in the String. 当字符串中有任何无效字符时,findInLine仅返回非空字符串。

我建议您使用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 <= 顺便说一句,它可能应该是我<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*/

 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java - 检查STRING是否只包含某些字符的最佳方法是什么? - Java - what is the best way to check if a STRING contains only certain characters? 检查字符串是否仅包含某些字符 - Checking if a string only contains certain characters Java-检查字符串是否仅包含某些字符(即DNA / RNA) - Java - Check if a string only contains certain characters (i.e. DNA/RNA) 如何验证文本框中的字符串仅包含2个字符和3个数字? - How to validate that a string from a textbox contains only 2 characters and 3 numbers? Java:如果仅包含字母字符,请验证文本字段输入 - Java: Validate textfield input if it only contains alphabetic characters 如何只接受Java中具有某些字符的String - How to only accept a String with certain characters in Java Java String - 查看字符串是否仅包含数字和字符而不包含单词? - Java String - See if a string contains only numbers and characters not words? 如何查找字符串是否包含“仅”特殊字符在java中 - How to find if a string contains “ONLY” Special characters in java 生成指定长度的随机字符串,该字符串仅包含指定字符(在Java中) - Generate a random string of specified length that contains only specified characters (in Java) 检查String是否仅包含这些字符{([])} - Check if String only contains these characters {([])}
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM