i need format telephone numbers in specific way. unfortunately business rules prohibit me doing front. (separate input boxes etc..)
the format needs +1-xxx-xxx-xxxx "+1" constant. (we don't business internationally)
here regex pattern test input:
"\\d*([2-9]\\d{2})(\\d*)([2-9]\\d{2})(\\d*)(\\d{4})\\d*" (which stole somewhere else)
then perform regex.replace() so:
regex.replace(telephonenumber, "+1-$1-$3-$5"); **this blows up** if telephone number has "+1" in string, prepends +1-+1-xxx-xxx-xxxx
can please help?
you can add (?:\+1\d*)? catch optional prefix before number. it's caught replaced if it's there.
you don't need use \d* before , after number. optional, don't change anything.
you don't need capture parts won't use, makes easier see ends in replacement.
str = regex.replace(str, @"(?:\+1\d*)?([2-9]\d{2})\d*([2-9]\d{2})\d*(\d{4})", "+1-$1-$2-$3"); you might consider using more specific \d* separators though, example [\- /]?. non-specific pattern risk catching that's not phone number, example changing "i have 234 cats, 528 dogs , 4509 horses." "i have +1-234-528-4509 horses.".
str = regex.replace(str, @"(?:\+1[\- /]?)?([2-9]\d{2})[\- /]?([2-9]\d{2})[\- /]?(\d{4})", "+1-$1-$2-$3");
Comments
Post a Comment