简体   繁体   English

检查字符串是否仅包含某些字符

[英]Checking if a string only contains certain characters

I have a string representing a 32 character long barcode made up of "|" 我有一个字符串,代表由“ |”组成的32个字符长的条形码 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 | 解释正则表达式:它会检查该字符串构成1个或多个字符的(这是什么+后缀一样)或者是:或者| . 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: 或者,您可以使用循环简单地编写5行算法:

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 | 由于您要求条形码的长度正好为32个字符,并且仅包含:和| 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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