简体   繁体   English

Java:如何检查字符串是否仅包含数字和连字符

[英]Java: How to check if a string contains only numbers and hyphens

I simply have a program that must read a ssn (xxx-xx-xxxx) and determine if the given ssn is valid.我只是有一个程序必须读取 ssn (xxx-xx-xxxx) 并确定给定的 ssn 是否有效。 I just need a way to check that the string only contains #'s and -'s.我只需要一种方法来检查字符串是否只包含# 和-。

import java.util.Scanner;
public class Prog7 {
  public static void main(String[] args) {

  Scanner input = new Scanner(System.in);
  System.out.print("Enter a SSN:");
  String ssn = input.next();

  if((ssn.substring(0, 4).indexOf('-') != 3) || (ssn.substring(4, 7).indexOf('-') != 2) || 
     (ssn.substring(ssn.length() - 5, ssn.length()).indexOf('-') != 0) ) {
     System.out.println(ssn + " is an invalid social security number");
  }
  else {
    System.out.println(ssn + " is a valid social security number");
  }

  }
}

Regular expression representing xxx-xx-xxxx where x stands for digit can be written as \d\d\d-\d\d-\d\d\d\d (note: \ in String literals is special character, so if you want to use it as symbol and pass to regex engine you will need to escape it with another \ , so String literal representing \d needs to be written as "\\d" ).表示xxx-xx-xxxx正则表达式,其中x代表数字,可以写为\d\d\d-\d\d-\d\d\d\d (注意:字符串文字中的\是特殊字符,所以如果您想将其用作符号并传递给正则表达式引擎,您需要用另一个\对其进行转义,因此表示\d的字符串文字需要写为"\\d" )。

Now you can simply use yourString.matches(regex) to see if regex matches whole yourString现在您可以简单地使用yourString.matches(regex)来查看正则表达式是否匹配整个yourString

So simple很简单

String ssn = input.next();

if(ssn.matches("\\d\\d\\d-\\d\\d-\\d\\d\\d\\d")){
    //here we know that `snn` is valid
}

should work fine.应该可以正常工作。

Improvements:改进:

You can make your regex more readable by using quantifiers .您可以使用quantifiers使您的正则表达式更具可读性。 For instance with {n} we can express how many times previous element must appear.例如,使用{n}我们可以表示前一个元素必须出现多少次。 So instead of \d\d\d we can write \d{3} .所以我们可以写\d{3}而不是\d\d\d

Also Scanner has methods which support regex, like hasNext(regex) to check if next token can be matched by regex. Scanner也有支持正则表达式的方法,比如hasNext(regex)来检查下一个标记是否可以被正则表达式匹配。 If it is not, we can simply consume it using next() and ask for new value:如果不是,我们可以简单地使用next()使用它并请求新值:

System.out.print("Enter a SSN:");
while(!input.hasNext("\\d{3}-\\d{2}-\\d{4}")){
    String invalid = input.next();
    System.out.print(invalid + " is not valid SSN. Please try again:");
}
//here we are sure that data provided by user represent valid SSN
String ssn = input.next();

Use a regular expression:使用正则表达式:

String ssn = input.next();
String pattern = "[0-9]{3}-[0-9]{2}-[0-9]{4}";
Pattern p = Pattern.compile(pattern);

Matcher m = p.matcher(ssn);
if (m.find( )) {
    System.out.println(ssn + " is an invalid social security number");
}else{
    System.out.println(ssn + " is a valid social security number");
}

And if you hate regex as much as I do, you could also iterate through characters comparing to ASCII values.如果你和我一样讨厌正则表达式,你也可以通过比较字符来迭代 ASCII 值。

public class HelloWorld{

 public static void main(String []args){
    System.out.println("Test A: " + checkSSN("123-45-6789"));
    System.out.println("Test B: " + checkSSN("12a-45-6789"));
    System.out.println("Test C: " + checkSSN("123-4"));
    System.out.println("Test D: " + checkSSN("123-45-20303"));
 }

 public static boolean checkSSN(String ssn) {
     int count = 0;
     for (char c : ssn.toCharArray()) {
         if (count == 3 || count == 6) {
             if (c != '-') {
                 System.out.println("Character" + c + "Not a dash, returning false");
                 return false;
             } 
         } else if (c < '0' || c > '9') {
             System.out.println("NaN, return false");
             return false;
         }
         count++;
     }
     if (count != 11) {
         System.out.println("Doesn't meet length criteria");
         return false;
     }
     return true;
 }

} }

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

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