I need a regular expression to convert US tel number to link

前端 未结 3 1321
慢半拍i
慢半拍i 2021-01-15 14:47

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.

相关标签:
3条回答
  • 2021-01-15 15:04

    Afaik, no phone enters the other characters, so why not replace [^0-9] with '' ?

    0 讨论(0)
  • 2021-01-15 15:07

    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 matches a, b, c, or any character between A and Z.
    It's not what you're trying to do.


    Edits

    In response to your updated regex:

    • 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 (.
    0 讨论(0)
  • 2021-01-15 15:08

    Here's a regex I wrote for finding phone numbers:

    (\+?\d[-\.\s]?)?(\(\d{3}\)\s?|\d{3}[-\.\s]?)\d{3}[-\.\s]?\d{4}
    

    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

    (m) => m.Value.Replace(' ', '')
    

    or something. working from memory here.

    0 讨论(0)
提交回复
热议问题