srsarkar7
srsarkar7

Reputation: 155

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!

Upvotes: 0

Views: 1263

Answers (3)

JB Nizet
JB Nizet

Reputation: 691635

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

Upvotes: 3

Zyn
Zyn

Reputation: 614

boolean isBarCode = barCode.matches( "[\\|\\:]*" );

Upvotes: 0

Humungus
Humungus

Reputation: 585

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
}

Upvotes: 0

Related Questions