Check if the string contains other characters

Asked

Viewed 49 times

1

I am developing a project that works with logical expressions, for example receive as input:

((TvF->T)^(T->F))->(~F<->T)

then I do all the validation to remove blanks, replace -> for - and <-> for -.

How can I perform a validation on the expression string to check if the user has entered any other character than one of these:

(,T,v,F,->,<->,~,),^?
  • You either only detect or want to remove too?

  • Regex in the method String.matches( ... ) to check for invalid characters

  • 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?

  • 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.

1 answer

0

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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.