string matching using regular expressions in java

前端 未结 1 713
自闭症患者
自闭症患者 2021-01-29 17:15

I want to match phone numbers like this, It should have 3 digits except 000,666 and any numbers between 900-999 followed by - then 2 digits followed by - then 4 digts. ex: 123-7

1条回答
  •  臣服心动
    2021-01-29 17:20

    I think this one should do the trick:

    ^(?!000|666|9\d{2})\d{3}-\d{2}-\d{4}$
    

    Edit: I find the negative look-ahead syntax in this thread.

    Edit 2: Here is a little code snippet for those who want to test it:

    import java.util.Scanner;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class Main {
    
        public static void main(String[] args) {
            Pattern pattern = Pattern.compile("^(?!000|666|9\\d{2})\\d{3}-\\d{2}-\\d{4}$");
            Scanner sc = new Scanner(System.in);
            while (true) {
                System.out.println("Next number :");
                Matcher matcher = pattern.matcher(sc.nextLine());
                if (matcher.find()) {
                    System.out.println("Matches");
                } else {
                    System.out.println("Doesn't match");
                }
            }
        }
    }
    

    0 讨论(0)
提交回复
热议问题