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();
}
}