Regex Syntax

Last Updated : Oct 16, 2023 |

This is a partial that considers regex items useful in the matching of telephone numbers.

String Position

Enclose a pattern with these to ensure matching to the full number.

Syntax

Description

^

Start of String: A ^ matches the start of the string.

$

End of String: A $ matches the end of the string.

Character Types

Syntax

Description

.

Any Character:

Match any character.

\d

Any Digit:

Match any digit. This just matches 0 to 9, not the dialing characters *, + and #.

\

Escape:

Use \ to escape characters that otherwise are regex commands. For example, \* matches a * digit, \+ matches a +.

  • Note: You do not need the escape character when the character to match is in [] brackets.

Group

Syntax

Description

|

Or:

Separate alternate possible matches. For example: 569|669 matches either 569 or 669. You can specify multiple alternates, for example: 569|669|779.

( )

Group:

Use ( ) brackets to group syntax. When performing digit translations, the element $1 in a translation represents the digits matched by the syntax in the first pair of ( ) brackets in the original pattern, $2 the second pair of brackets, and so on.

[ ]

Range of Characters:

Use [ ] square brackets to group specific characters or a character range to match. For example: [569] matches a 5, 6 or 9; [5-7] matches a 5, 6 or 7; [0-9*#+] matches any telephone number character.

  • When used in [ ] brackets, characters such as + and * do not need a preceding \ escape.

  • Use a ^ character inside the [] brackets to perform a non-match. For example: [^569] matches any digit other than a 5, 6 or 9.

Number of Matches

Syntax

Description

?

Match zero or one:

Use a ? question mark to match zero or one occurrences of the preceding element. For example: ^\+? matches numbers beginning with or without a + prefix.

*

Match zero or more:

Use an * to match zero or more occurrences of the preceding element. For example: ^1.*$ matches 1 and numbers beginning with a 1. To match an actual *, use \*.

+

Match one or more:

Use a + plus sign to match one or more occurrences of the preceding element. For example: ^1.+$ matches number beginning with a 1 but not just 1. To match an actual +, use \+.

{n}

Match N times:

Match the preceding item exactly n times. For example: ^.{3} matches 3-digit numbers.

{n,}

Match N or more times:

Match the preceding item n or more times. For example: ^. {3,}$ matches 3-digit or longer numbers.

{,m}

Match up to M times:

Match the preceding item up to m times. For example: ^.{,4}$ matches numbers up to 4-digits long.

{n,m}

Match between N to M times:

Match the preceding item at least m times, but no more than n times. For example: ^.{3,4}$ matches 3 and 4-digit numbers.