繁体   English   中英

如果字符串与正则表达式不完全匹配,我如何忽略字符串?

[英]How can I disregard a String if the String did not match entirely with the regex?

比如我想忽略这个String 123+456 78912,但是正则表达式匹配了前三个字符,所以返回true。 有没有办法在不创建新的正则表达式的情况下做到这一点?

正则表达式还必须符合以下条件:

+0 (123) 456-789-ABcd

+0 (123) 456

(123) 234 345-456

1111111111111

+1 123 123 123 123

123

123-(456)

123 (456) 789

+(电话)

(123)

private boolean checkValidity(String number){
    // Check value using regex and set value to field only if sastify these rules:
    //
    //   Phone number is split using space or dash
    //   Prefix may have +
    //   1st/2nd group have (), maximum only one grp
    //   grp contains number/upper/lowercase, at least two symbols in length
    //   1st grp may have one symbol in length

    Pattern pattern = Pattern.compile("^\\+?\\d{0,100}(\\w+[ -]+)*([ -]+\\(\\w+\\)[ -]+|[ -]+\\(\\w+\\)$|\\(\\w+\\)[ -]+|\\(\\w+\\)$){0,2}([ -]?\\w)*");
    Matcher matcher = pattern.matcher(number);
    boolean matchFound = matcher.find();

    if(matchFound){
        return true;
    }
    System.out.println("Wrong number format!");
    return false;
}

使用 matcher.group().equals 检查原始值和匹配值

private boolean checkValidity(String number){
        //check value using regex and set value to field only if sastify these rules:
        //Phone number is split using space or dash
        //Prefix may have +
        //1st/2nd group have (), max only 1 grp
        //grp contains number/upper/lowercase, at least 2 symbols in length
        //1st grp may have 1 symbol in length

        Pattern pattern = Pattern.compile("(^\\+?\\d{0,100}(\\w+[ -]+)*([ -]+\\(\\w+\\)[ -]+|[ -]+\\(\\w+\\)$|\\(\\w+\\)[ -]+|\\(\\w+\\)$){0,1}([ -]?\\w{2,100})*)");
        Matcher matcher = pattern.matcher(number);
        boolean matchFound = matcher.find();
        //System.out.println(matcher.group());
        if(matchFound && matcher.group().equals(number)){
            return true;
        }
        System.out.println("Wrong number format!");
        return false;
    }

暂无
暂无

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

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