简体   繁体   中英

Checking if a string only contains certain characters

I have a string representing a 32 character long barcode made up of "|" and ":".

I want to check the validity of any given string to make sure it is a barcode. One of the tests is to check that the only symbols it contains are the two mentioned above. How can I check that?

I first I was using a delimiter, but I don't think that is the right way to go about this.

public boolean isValidBarCode (String barCode)
{
  barCode.useDelimiter ("[|:]");
  if (barCode.length() == 32)
  {
       return true;
  }         

  else 
  {
      return false;
  }

I know there are other things I need to check in order to validate it as a barcode, but I'm asking only for the purposes of checking the symbols within the given string.

I'm a beginner programmer, so the help is greatly appreciated!

You can use a regex:

boolean correct = string.matches("[\\:\\|]+");

Explanation for the regex: it checks that the string is constituted of 1 or more characters (that's what the + suffix does) being either : or | . We would normally write [:|]+ , but since : and (I think) | are special characters in regexes, they need to be escaped with a backslash. And backslashes must be escaped in a string literal, hence the double backslash.

Or you can simply code a 5 lines algorithm using a loop:

boolean correct = false;
for (int i = 0; i < string.length() && correct; i++) {
    char c = string.charAt(i);
    if (c != ':' && c != '|') {
        correct = false;
    }
}
boolean isBarCode = barCode.matches( "[\\|\\:]*" );

Since you require the barcode to be exactly 32 characters long and consist only of the : and | characters, you should use a combination of length and regex checking:

boolean isCorrect = barCode.matches( "[\\|\\:]*" );
if(isCorrect && barCode.length() == 32) {
    //true case
} else {
    //false case
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM