Basically, the input field is just a string. People input their phone number in various formats. I need a regular expression to find and convert those numbers into links.
Input examples:
(201) 555-1212
(201)555-1212
201-555-1212
555-1212
Here's what I want:
<a href="tel:(201)555-1212">(201) 555-1212</a> - Notice the space is gone
<a href="tel:(201)555-1212">(201)555-1212</a>
<a href="tel:201-555-1212">201-555-1212</a>
<a href="tel:555-1212">555-1212</a>
I know it should be more robust than just removing spaces, but it is for an internal web site that my employees will be accessing from their iPhone. So, I'm willing to "just get it working."
Here's what I have so far in C# (which should show you how little I know about regular expressions):
strchk = Regex.Replace(strchk, @"\b([\d{3}\-\d{4}|\d{3}\-\d{3}\-\d{4}|\(\d{3}\)\d{3}\-\d{4}])\b", "<a href='tel:$&'>$&</a>", RegexOptions.IgnoreCase);
Can anyone help me by fixing this or suggesting a better way to do this?
EDIT:
Thanks everyone. Here's what I've got so far:
strchk = Regex.Replace(strchk, @"\b(\d{3}[-\.\s]\d{3}[-\.\s]\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]\d{4}|\d{3}[-\.\s]\d{4})\b", "<a href='tel:$1'>$1</a>", RegexOptions.IgnoreCase);
It is picking up just about everything EXCEPT those with (nnn) area codes, with or without spaces between it and the 7 digit number. It does pick up the 7 digit number and link it that way. However, if the area code is specified it doesn't get matched. Any idea what I'm doing wrong?
Second Edit:
Got it working now. All I did was remove the \b
from the start of the string.
Here's a regex I wrote for finding phone numbers:
It's pretty flexible... allows a variety of formats.
Then, instead of killing yourself trying to replace it w/out spaces using a bunch of back references, instead pass the match to a function and just strip the spaces as you wanted.
C#/.net should have a method that allows a function as the replace argument...
Edit: They call it a `MatchEvaluator. That example uses a delegate, but I'm pretty sure you could use the slightly less verbose
or something. working from memory here.
Afaik, no phone enters the other characters, so why not replace
[^0-9]
with''
?Remove the
[]
and add\s*
(zero or more whitespace characters) around each\-
.Also, you don't need to escape the
-
. (You can take out the\
from\-
)Explanation:
[abcA-Z]
is a character group, which matchesa
,b
,c
, or any character betweenA
andZ
.It's not what you're trying to do.
Edits
In response to your updated regex:
[-\.\s]
to[-\.\s]+
to match one or more of any of those characters (eg, a-
with spaces around it)\b
doesn't match the boundary between a space and a(
.