0

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();
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Diego Palomar
  • 6,958
  • 2
  • 31
  • 42

3 Answers3

2

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("[^/\\\\&<>\"]*")
Robin
  • 9,415
  • 3
  • 34
  • 45
1

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:

"^[^/\\\\/&<>\"]*$"
Trygve Flathen
  • 686
  • 7
  • 15
1

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

if (subjectString.matches("^(?!.*[\\\\/&<>\"]).*$")) {
        // VALID STRING
    } else {
        // INVALID STRING
    } 
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268