简体   繁体   English

java中使用正则表达式进行字符串匹配

[英]string matching using regular expressions in java

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 digits .它应该有3 位数字,但000,666900-999之间的任何数字后跟“-”,然后是2 位数字后跟“-”,然后是4 位数字

For example:例如:

123-75-3456  is a match
000- 23-3452 is not a match (no 000)
915-23-4534 is not a match (greater than 900)

This is where I currently stand:这是我目前的立场:

[0-9&&^[000,666,[900-999]]{3}-[0-9]{2}-[0-9]{4}

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:编辑 2:对于那些想要测试它的人来说,这是一个小代码片段:

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

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

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