我需要一个正则表达式转换成美国的电话号码链接 [英] I need a regular expression to convert US tel number to link

查看:291
本文介绍了我需要一个正则表达式转换成美国的电话号码链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,输入字段仅仅是一个字符串。人输入各种格式的电话号码。我需要一个正则表达式查找和这些数字转化为链接

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.

输入例子:

(201) 555-1212
(201)555-1212
201-555-1212
555-1212

下面就是我想要的:

<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>



我知道这应该不仅仅是去掉空格较为强劲,但它是一个内部网站,我的员工将他们的iPhone要访问。所以,我愿意只得到它的工作。

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."

下面是我到目前为止在C#中(这应该告诉你我是多么少了解正则表达式)

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?

编辑:

谢谢大家。下面是我到目前为止有:

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);



据拿起刚才的一切除了那些(NNN)区域代码,带或不带之间有空格它和7位数字。它拿起7位数字,并将其链接的方式。然而,如果指定了区号它不会匹配。 ?知不知道我做错了。

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?

第二个编辑:

了现在的工作。我所做的只是从字符串的开始删除 \b

Got it working now. All I did was remove the \b from the start of the string.

推荐答案

删除 [] 并添加 \s * 每个左右(零个或多个空白字符) \ -

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 \-)

说明: [ABCA-Z] 字符组的,它匹配 A b C ,或之间的任何字符 A 以Z 。结果
这不是你想要做的事。

Explanation: [abcA-Z] is a character group, which matches a, b, c, or any character between A and Z.
It's not what you're trying to do.

在应对更新的正则表达式:

In response to your updated regex:


  • 更改 [ - \.\s] [ - \.\s] + 来匹配任何这些字符中的一个或多个(例如, - )

  • 的问题是, \b 空格和

  • 之间的边界不匹配
  • Change [-\.\s] to [-\.\s]+ to match one or more of any of those characters (eg, a - with spaces around it)
  • The problem is that \b doesn't match the boundary between a space and a (.

这篇关于我需要一个正则表达式转换成美国的电话号码链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆