Pregunta

I need to write a regular expression to validate the input in a form. I want to restrict the use of these characters: \ / & < > " . Everything else is allowed.

Examples of valid inputs are: My Basket, Groceries, Fruits, £$%, and +=.

Examples of invalid inputs are: A&B, A > B, 2 / 3, and A<>C.

Below is the code I'm using which is not working properly, because it returns as valid some inputs than actually are invalids.

public class Main {

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        while (true) {
            System.out.print("\nEnter text: ");
            String inputText = br.readLine();

            System.out.println("\nThe input is " + (isValidInput(inputText) ? "valid" : "invalid"));
        }
    }

    public static boolean isValidInput(String inputText) {

        Pattern p = Pattern.compile("[^/\\\\/&<>\"]");
        Matcher matcher = p.matcher(inputText);

        return matcher.find();
    }
}
¿Fue útil?

Solución

Finding [^/\\\\&<>\"] will only check that at least one of the character isn't a forbidden one.

If you want to check that the whole string is made of allowed characters, you have to anchor the regex:

Pattern.compile("^[^/\\\\&<>\"]*$").matcher(inputText).find();

With ^$ matching the beginning and end of the string.

Or, as pointed out by @devnull, you can use String.matches wihch anchors the regex by default:

inputText.matches("[^/\\\\&<>\"]*")

Otros consejos

Your find will succeed if it finds any character that is not in your list, regardless of the presence of such characters in other parts of the string. Try:

"^[^/\\\\/&<>\"]*$"

Uses negative lookahead to find if the string contains \ / & < > "

if (subjectString.matches("^(?!.*[\\\\/&<>\"]).*$")) {
        // VALID STRING
    } else {
        // INVALID STRING
    } 
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top