简体   繁体   中英

check if a string only contains specified characters

I want to check that a string only contains letters, a-zA-Z , numbers 0-9 , and operators (+=-*/^)

For example, the following expression would be permissible: 3 + 5(x^2)

For example, the following expression would not be permissible: 3 $+ 5(x^2)

Would I use the matches function to do this?

I tried:

// contains only operators, numbers, or letters
if(!exp.matches("[(+=-*/^)a-zA-Z0-9]")) { 
    return false;
}

I also tried escaping the asterisk, but it didn't work.

You should have escaped - or put it at the start/end of the character class, else it creates a range . Note that [=-*] range is invalid :

在此输入图像描述

Also, you need a quantifier, + to match 1 or more chars, * to match 0 or more.

Use

if(!exp.matches("[a-zA-Z0-9+=*/^()-]+")) { 
        return false;
}

If you do not need to match ( and ) , remove them from the character class.

Also, since the String#matches() requires a full string match, no anchors at the start and end of the regular expression are necessary.

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