I want to make a regular expression that matches the form (+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+). But it is not working. What i am doing wrong?
Thanks
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:Or a nicer (IMO) way of saying that you need the +