Regular Expressions 101

Save & Share

Flavor

  • PCRE2 (PHP >=7.3)
  • PCRE (PHP <7.3)
  • ECMAScript (JavaScript)
  • Python
  • Golang
  • Java 8

Function

  • Match
  • Substitution
  • List
  • Unit Tests
/
^(1?)(?:((\s?\(\d{3}\)\s?|\s?\d{3}\s?)\-?\d{3}\s?\-?\d{4}$))
/
gm
^ asserts position at start of a line
1st Capturing Group
(1?)
1
matches the character 1 with index 4910 (3116 or 618) literally (case sensitive)
Non-capturing group
(?:((\s?\(\d{3}\)\s?|\s?\d{3}\s?)\-?\d{3}\s?\-?\d{4}$))
2nd Capturing Group
((\s?\(\d{3}\)\s?|\s?\d{3}\s?)\-?\d{3}\s?\-?\d{4}$)
3rd Capturing Group
(\s?\(\d{3}\)\s?|\s?\d{3}\s?)
1st Alternative
\s?\(\d{3}\)\s?
\s
matches any whitespace character (equivalent to [\r\n\t\f\v ])
? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy)
\( matches the character ( with index 4010 (2816 or 508) literally (case sensitive)
\d
matches a digit (equivalent to [0-9])
{3} matches the previous token exactly 3 times
\) matches the character ) with index 4110 (2916 or 518) literally (case sensitive)
\s
matches any whitespace character (equivalent to [\r\n\t\f\v ])
? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy)
2nd Alternative
\s?\d{3}\s?
\s
matches any whitespace character (equivalent to [\r\n\t\f\v ])
? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy)
\d
matches a digit (equivalent to [0-9])
{3} matches the previous token exactly 3 times
\s
matches any whitespace character (equivalent to [\r\n\t\f\v ])
? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy)
\-
matches the character - with index 4510 (2D16 or 558) literally (case sensitive)
? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy)
\d
matches a digit (equivalent to [0-9])
{3} matches the previous token exactly 3 times
\s
matches any whitespace character (equivalent to [\r\n\t\f\v ])
? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy)
\-
matches the character - with index 4510 (2D16 or 558) literally (case sensitive)
? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy)
\d
matches a digit (equivalent to [0-9])
{4} matches the previous token exactly 4 times
$ asserts position at the end of a line
Global pattern flags
g modifier: global. All matches (don't return after first match)
m modifier: multi line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)
Your regular expression does not match the subject string.Try launching the debugger to find out why.

Regular Expression
No Match

/
/
gm

Test String