开发者

Regex Validation only works with one single Character

开发者 https://www.devze.com 2023-03-25 05:24 出处:网络
I want to check if a userInput is free from special characters, here is my code: public class ValidateHelper {

I want to check if a userInput is free from special characters, here is my code:

public class ValidateHelper {

public boolean userInputContainsNoSpecialCharacters(String开发者_如何学编程 input){

        Pattern p = Pattern.compile("[a-zA-Z_0-9 ]");
        Matcher m = p.matcher(input);
        boolean b = m.matches();

        if (b)
            return true;
        else
            return false;
}

}

This works if I type one character in a textfield -> "a" in the textfield -> the method returns true "ab" in the textfield -> method returns false. can somebody help please? beste regards Daniel


Pattern p = Pattern.compile("[a-zA-Z_0-9 ]+");


Change "[a-zA-Z_0-9 ]" to "[a-zA-Z_0-9 ]+"

The + matches "one or more" of that group.


That is because you are using the character class []. If you would like to capture a limited amount, any amount or a range of characters you need to modify it.

[a-zA-Z_0-9 ]+ //1 or more characters
[a-zA-Z_0-9 ]{1,5} //1 - 5 characters


You should use the following regex:

[A-Za-z0-9]+


change your pattern from [a-zA-Z_0-9 ] to ^[a-zA-Z_0-9 ]*$ (for 0 or more valid characters) or ^[a-zA-Z_0-9 ]+$ if you want to ensure they enter a value

A + indicates 1 or more repetitions.

A * indicates 0 or more repetitions.

The ^ and $ denote the start end of the line respectively.

0

精彩评论

暂无评论...
验证码 换一张
取 消