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

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

问题描述

基本上,输入字段只是一个字符串.人们以各种格式输入他们的电话号码.我需要一个正则表达式来查找这些数字并将其转换为链接.

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, @"([d{3}-d{4}|d{3}-d{3}-d{4}|(d{3})d{3}-d{4}])", "<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, @"(d{3}[-.s]d{3}[-.s]d{4}|(d{3})s*d{3}[-.s]d{4}|d{3}[-.s]d{4})", "<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?

第二次

现在开始工作了.我所做的只是从字符串的开头删除 .

Got it working now. All I did was remove the  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] 是一个字符组,匹配abc,或 AZ 之间的任何字符.
这不是你想要做的.

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]+ 以匹配这些字符中的一个或多个(例如,- 周围有空格)
  • 问题在于  与空格和 (.
  • 之间的边界不匹配
  • Change [-.s] to [-.s]+ to match one or more of any of those characters (eg, a - with spaces around it)
  • The problem is that  doesn't match the boundary between a space and a (.

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

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