Just to validate whether the characters are valid you can do something like this:
String operation = "((TvF->T)^(T->F))->(~F<->T)";
Set<String> validStrings = new HashSet<String>(
Arrays.asList(new String[]{ "(", "T", "v", "F", "->", "<->", "~", ")", "^", "?" })
);
Set<Character> combinedChars = new HashSet<Character>(
Arrays.asList(new Character[]{ '-', '<' })
);
boolean isValidOp = true;
StringBuilder subString = new StringBuilder();
for (int i = 0; i < operation.length(); i++) {
subString.append(operation.charAt(i));
if (validStrings.contains(subString.toString())) {
subString = new StringBuilder();
} else {
if (!combinedChars.contains(operation.charAt(i))) {
isValidOp = false;
break;
}
}
}
System.out.println(isValidOp);
But for what validation of logical expressions will be necessary something more, as mentioned in the comments would have to ensure that for example the parentheses are closed when opened.
You either only detect or want to remove too?
– user28595
Regex in the method
String.matches( ... )
to check for invalid characters– Valdeir Psr
I would like to detect only, to warn the user that he has entered an invalid expression. The Matches I would use in the case String.Matches("(Tvf ~"); for it to return if it found other things besides these characters in the string?
– Gabriel Longatti
I don’t think this validation would be enough, because you will need to validate whether the expression is coherent as well; for example, validate that all parentheses have been closed and are correctly nested. I think you’ll need to implement a lexicon analyser.
– Douglas