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

前端 未结 3 1356
慢半拍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: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.

提交回复
热议问题