简体   繁体   English

正则表达式不起作用(Java)

[英]Regular expression is not working (Java)

I want to make a regular expression that matches the form (+92)-(21)-1234... . 我想做一个正则表达式,匹配形式(+92)-(21)-1234 ...。 I made this program 我做了这个程序

public static void main(String[] args) {

    // A regex and a string in which to search are specifi ed
    String regEx = "([+]\\d{2})-(\\d{2})-\\d+";
    String phoneNumber = "(+92)-(21)-1234567890";

    // Obtain the required matcher
    Pattern pattern = Pattern.compile(regEx);
    Matcher matcher = pattern.matcher(phoneNumber);

    if (matcher.matches()) {
        System.out.println("Phone Number Valid");
    } else {
        System.out.println("Phone Number must be in the form (+xx)-(xx)-xxxxx..");
    }

} //end of main()

The regular expression i created like starts with the bracket( ( ), + [+] , two numbers( \\d{2} ), bracket close( ) ), a dash( - ), start bracket( ( ), two numbers( \\d{2} ), bracket close( ) ), a dash( - ) and then any number of digits( \\d+ ). 我创建的正则表达式以方括号( ),+ [+] ,两个数字( \\ d {2} ),方括号close( ),破折号( - ),开始方括号( ),两个数字( \\ d {2} ),括号close( ),短划线( - ),然后是任意位数( \\ d + )。 But it is not working. 但这是行不通的。 What i am doing wrong? 我做错了什么?

Thanks 谢谢

The regular expression i created like starts with the bracket(() 我创建的正则表达式以括号(()开始

No, it starts with a grouping construct - that's what an unescaped ( means in a regular expression. I haven't looked at the rest of the expression in detail, but try just escaping the brackets: 不,它始于分组构造-这是未转义的(在正则表达式中表示的意思。我没有详细介绍该表达式的其余部分,但尝试转义括号:

String regEx = "\\([+]\\d{2}\\)-\\(\\d{2}\\)-\\d+";

Or a nicer (IMO) way of saying that you need the + 或更好的(IMO)说法,您需要+

String regEx = "\\(\\+\\d{2}\\)-\\(\\d{2}\\)-\\d+";

转义括号和破折号

You need to escape the parantheses (as Jon already mentioned they create a capturing group): 您需要逃脱寄生虫(如乔恩已经提到的,它们创建了一个捕获组):

public static void main(String[] args) {

     // A regex and a string in which to search are specifi ed
     String regEx = "\\([+]\\d{2}\\)-\\(\\d{2}\\)-\\d+";
     String phoneNumber = "(+92)-(21)-1234567890";

     // Obtain the required matcher
     Pattern pattern = Pattern.compile(regEx);
     Matcher matcher = pattern.matcher(phoneNumber);

     if (matcher.matches()) {
         System.out.println("Phone Number Valid");
     } else {
         System.out.println("Phone Number must be in the form (+xx)-(xx)-xxxxx..");
     }

}

Output: 输出:

Phone Number Valid 电话号码有效

The correct regex is 正确的正则表达式是

[(][+]\\d{2}[)]-[(]\\d{2}[)]-\\d+

You just needed to put your brackets between [ and ]. 您只需要将括号放在[和]之间。

if the plus symbol is always there you could just write \\\\+ , if it may or may not be there, \\\\+? 如果加号始终存在,则可以只写\\\\+ ,如果可能存在或不存在,则\\\\+? . You should escape all regex-specific characters like this 您应该像这样转义所有正则表达式专用字符

String regEx = "\\(\\+\\d{2}\\)-\\(\\d{2}\\)-\\d+";

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

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