Home > Back-end >  String should only contain characters '?', '0' and '1'
String should only contain characters '?', '0' and '1'

Time:11-22

Im trying to solve a problem which reads only characters '?', '0' and '1' from the console. I have been using the following if statement, but it only works when all three are included in the string.

How should the statement look like if I only want '?', '0' and '1'? I want the program to stop if I use for instance "10?=".

 if(text.contains("?") && text.contains("0") && text.contains("1"))
        {
            //do something
        }

CodePudding user response:

You can use regex for this with the following pattern: [?01] which means 1 or more instances of the characters ?, 0 or 1. if you want to limit it to 0 or more instances of any of them you can use this pattern instead: [?01]* or for exactly 1 you can just omit the * at the end ([?01])

The usage would be as follow:

private Pattern pattern = Pattern.compile("[?01] ");

private boolean isMatching(String s) {
   return pattern.matcher(s).matches();
}

An example of the usage would be (please note that in this case both the function and the pattern need to be static):

 public static void main(String[] args) {
     System.out.println(isMatching("?"));
     System.out.println(isMatching("?A"));
     System.out.println(isMatching("N?"));
     System.out.println(isMatching("3"));
     System.out.println(isMatching("01"));
}

Which will follow this output:

true
false
false
false
true

CodePudding user response:

You should use || (OR) and also pot character betweeen ' ' not " ".

So:

if(text.contains('?') || text.contains('0') || text.contains('1'))
        {
            //do something
        }
  • Related