正则表达式组合

时间:2018-01-03 19:26:26

标签: java regex

正则表达式是否可以组合两个验证? 只要在声明中给出一系列8位数字(12345678)以及空格(1234 5678) 正则表达式应该抛出错误。以及字母和其他特殊字符的验证。

例如:1234公寓,#23建筑州234 456(有效一个)

1234公寓,#23建筑状态1234 5678 overhill(因系列/连续8位数无效)

677 flat,@(23)floor,up state 56789123 state UK(因连续8位数而无效)

1 个答案:

答案 0 :(得分:1)

代码

See regex in use here

(?:\d *){8}

用法

See code in use here

import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        final String regex = "(?:\\d *){8}";
        final String[] strings = {
            "1234 offshore address1234 Some locations",
            "1234 5678 offshore some location"
        };

        final Pattern pattern = Pattern.compile(regex);

        for (String s: strings) {
            Matcher matcher = pattern.matcher(s);
            if(!matcher.find()) {
                System.out.println(s);
            }
        }
    }
}

结果

输入

1234 offshore address1234 Some locations
1234 5678 offshore some location

输出

下面显示了不匹配的字符串。

1234 offshore address1234 Some locations

说明

(?:\d *){8}匹配一个数字后跟任意数量的空格正好8次

相关问题