I'm trying to remove the +1 (country code) from a phone number (I'm working on a normalization project). For example, the user has a phone number in the format of +1(703)-555-5787 and he wants it to be (703)-555-5787 (without the +1 at the front).
My theory is that I can search through the phoneNum string based on a regex pattern. Once it is found, I can print it or do whatever I like. My code is seen below:
public static String normalizePrefix(final String phoneNum) {
String ret = phoneNum;
if (!phoneNum.contains("+1")) {
logger.log(Level.INFO, "input phone number doesn't contain country code (+1)");
}
else {
String regex = "(\\+1)([2-9][0-9][0-9])-([2-9][0-9]{2})-([0-9]{4})";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(phoneNum);
if (phoneNum.matches(regex)){
ret = m.group().substring(2, m.end());
}
}
logger.log(Level.INFO, phoneNum + "-->" + ret);
return ret;
}
What am I missing?
matches
would try to match the pattern exactly ..
So in case you have phone number in between the string your regex won't work.
use Matcher's find method
if (m.find())
{
ret = m.group().substring(2, m.group().length());
}
Try the regex :
String regex = "\\([0-9]{3}\\)-[0-9]{3}-[0-9]{4}";
And modify the if block as :
if (m.find()){
ret = m.group(0);
}
I've tried and tested here the following regular expression:
String regex = "\\([0-9]{3}\\)-[0-9]{3}-[0-9]{4}";
Afterwards, modify the if block:
if (m.matches()){
ret = m.group(2);
}
This should always return the phone number, no matter if the +1 prefix is there or not.
So, I figured it out (I tried to answer my question about 20 minutes after I asked it but SO wouldn't let me). Nonetheless, thank you all for your feedback and support, I'm truly grateful.
Here was my mistake:
My regex was String regex = "(\\\\+1)([2-9][0-9][0-9])-([2-9][0-9]{2})-([0-9]{4})";
but my phoneNum string was +1(703)-555-4563. It was giving me errors because the regex was looking for a number of this format instead: +1703-555-4563 (without the () around the area code). Thus, finding a substring was impossible because it did not exist. My regex should have been String regex = "(\\\\+1)(\\\\([2-9][0-9][0-9]\\\\))-([2-9][0-9]{2})-([0-9]{4})";
.
Thank you everyone for your help!
Much appreciated :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.