Java 使用正则表达式在索引附近的未封闭组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22901462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 18:47:37  来源:igfitidea点击:

Unclosed Group near index using Regex

javaregex

提问by webminer07

I am trying to test a phone numbers format using regular expressions, regex, and when I run the Pattern.compile I receive the error java.util.regex.PatternSyntaxException: Unclosed group near index 34

我正在尝试使用正则表达式、regex 测试电话号码格式,当我运行 Pattern.compile 时,我收到错误java.util.regex.PatternSyntaxException: Unclosed group near index 34

public String checkPhoneNum(String inPhoneNum)
{
    Pattern checkRegex = Pattern.compile("(\([0-9]{3}\)([0-9]{3}(-)[0-9]{4})");
    Matcher regexMatcher = checkRegex.matcher(inPhoneNum);

    if(regexMatcher.find())
    {
        return inPhoneNum;
    }
    else
        return null;
}

is the string (\\([0-9]{3}\\)([0-9]{3}(-)[0-9]{4})not correctly written for format (000)111-2222?

(\\([0-9]{3}\\)([0-9]{3}(-)[0-9]{4})是否为格式 (000)111-2222 编写的字符串不正确?

采纳答案by Szymon

You are missing one closing parenthesis in the first matching group:

您在第一个匹配组中缺少一个右括号:

It should be

它应该是

Pattern checkRegex = Pattern.compile("(\([0-9]{3}\))([0-9]{3}(-)[0-9]{4})");

As it is:

原样:

( - start of mathing group 
\( - matches (  
[0-9]{3} - 3 digits  
\) - matches )  
) - end of matching group (this is the one you missed)