简体   繁体   English

正则表达式,用于检查允许的字符在Java中不起作用

[英]Regular expression to check allowed characters not working in Java

I have the following method to check allowed characters: 我有以下方法来检查允许的字符:

private boolean checkIfAllCharsAreValid(String test) {
    boolean valid = false;
    if (test.matches("^[a-zA-Z0-9,.;:-_'\\s]+$")) {
        valid = true;
    }
    return valid;
}

but if test has the character - in it the match return false. 但是如果test有字符-在匹配中返回false。 Do i have to escape the - ? 我必须逃避-

Inside [ ... ] the - symbol is treated specially. [ ... ]里面-符号是专门处理的。 (You use it yourself in this special purpose in the beginning of your expression where you have az .) (你在表达式的开头用你的az这个特殊目的自己使用它。)

You need to escape the - character 你需要逃避-角色

[a-zA-Z0-9,.;:\-_'\s]
              ^

or put it last (or first) in the [...] expression like 或者把它放在[...]表达式中的最后(或第一个)

[a-zA-Z0-9,.;:_'\s-]
                   ^

Some further notes: 进一步说明:

  • Technically speaking all characters are valid in the empty string, so I would change from + to * in your expression. 从技术上讲,所有字符在空字符串中都有效,所以我会在表达式中从+更改为*

  • String.matches checks the full string, so the ^ and $ are redundant. String.matches检查完整的字符串,因此^$是多余的。

  • Your entire method could be wirtten as 你的整个方法可以被视为

     return test.matches("[a-zA-Z0-9,.;:_'\\\\s-]*"); 

A - in a character class surrounded on both sides is a regex meta character to denote range. A -在两侧包围的字符类中是用于表示范围的正则表达式元字符。

To list a literal - in a char class you escape the - in the char class: 要列出一个文字-在char类中,你在char类中转义-

if (test.matches("^[a-zA-Z0-9,.;:\\-_'\\s]+$")) 
                                 ^^^ 

or place the - at the end of char class: 或者把-放在char类的末尾:

if (test.matches("^[a-zA-Z0-9,.;:_'\\s-]+$")) 
                                      ^

or place the - at the beginning of char class: 或者把-放在char类的开头:

if (test.matches("^[-a-zA-Z0-9,.;:_'\\s]+$")) 
                    ^

您可以将-放在字符组的开头,以便它不会被解释为字符范围。

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

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