Converting phone numbers to links using Grep in BBEdit

When I want to turn phone numbers in web copy into tappable links for smartphones — without relying on mobile browsers to do so — this regular expression saves me a lot of time. Simple search-and-replace fails because if the formatting varies even a little from number to number it becomes a time-consuming, manual process.

Typical input phone number variations:

BBEdit screenshot of phone numbers

Search pattern:
1?-? ?(?(ddd))?-? ?(ddd)-? ?(dddd)

The question marks in this pattern allow it to work with or without a leading 1, spaces, parentheses (), or hyphens -.

Replacement pattern:
<a class=tel href="tel:+1\1\2\3">(\1) \2-\3</a>

BBEdit’s Find… window (with Grep enabled):

BBEdit Find… window with Grep pattern

The result of clicking the Replace All button:

Phone numbers converted to HTML links in BBEdit using Grep (regular expressions)

Which renders as tappable links (complete with a tel class you can use to style them with a suitably-sized tap target on smartphones):

HTML preview in BBEdit

Using a text editor capable of search-and-replace using regular expressions — like BBEdit (It still doesn’t suck®) — allows you to save the pattern in the Find… window’s Patterns list (the “g” button) for later reuse.

More on BBEdit-specific Grep

My favourite reference for BBEdit-specific Grep for years now has been Cari D. Burstein’s BBEdit Grep Tutorial, which hasn’t needed updating since 2004 (nearly 12 years as of this writing).