java中使用正则表达式进行字符串匹配 [英] string matching using regular expressions in java

查看:3358
本文介绍了java中使用正则表达式进行字符串匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望匹配这样的电话号码,
它应该有3位数字,除了000,666和900-999之间的任何数字后跟 - 然后是2位数后跟 - 然后4位数。
ex:123-75-3456是数学
000- 23-3452不匹配(没有000)
915-23-4534不匹配(大于900)
有人可以帮忙吗?
对不起忘了添加我尝试的内容,
[0-9&& ^ [000,666,[900-999]] {3} - [0-9] {2} - [0-9 ] {4}

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-75-3456 is a math 000- 23-3452 is not a match (no 000) 915-23-4534 is not a match (greater than 900) can someone help? Sorry forgot to add what i tried, [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}$

编辑:我在此主题

编辑2:这是一个小代码片段给那些想要测试它的人:

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

这篇关于java中使用正则表达式进行字符串匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆