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
"
time\s(\w+\s*\{\s\n(\s{2,8}\w+\s\w+\s.+\n){1,2}\})
"
g
time
matches the characters time literally (case sensitive)
\s matches any whitespace character (equivalent to [\r\n\t\f\v  ])
1st Capturing Group
(\w+\s*\{\s\n(\s{2,8}\w+\s\w+\s.+\n){1,2}\})
\w
matches any word character (equivalent to [a-zA-Z0-9_])
+ matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
\s
matches any whitespace character (equivalent to [\r\n\t\f\v  ])
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
\{ matches the character { with index 12310 (7B16 or 1738) literally (case sensitive)
\s matches any whitespace character (equivalent to [\r\n\t\f\v  ])
\n matches a line-feed (newline) character (ASCII 10)
2nd Capturing Group
(\s{2,8}\w+\s\w+\s.+\n){1,2}
{1,2} matches the previous token between 1 and 2 times, as many times as possible, giving back as needed (greedy)
A repeated capturing group will only capture the last iteration. Put a capturing group around the repeated group to capture all iterations or use a non-capturing group instead if you're not interested in the data
\s
matches any whitespace character (equivalent to [\r\n\t\f\v  ])
{2,8} matches the previous token between 2 and 8 times, as many times as possible, giving back as needed (greedy)
\w
matches any word character (equivalent to [a-zA-Z0-9_])
+ matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
\s matches any whitespace character (equivalent to [\r\n\t\f\v  ])
\w
matches any word character (equivalent to [a-zA-Z0-9_])
+ matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
\s matches any whitespace character (equivalent to [\r\n\t\f\v  ])
.
matches any character (except for line terminators)
+ matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
\n matches a line-feed (newline) character (ASCII 10)
\} matches the character } with index 12510 (7D16 or 1758) literally (case sensitive)
Global pattern flags
g modifier: global. All matches (don't return after first match)
Your regular expression does not match the subject string.

Regular Expression
No Match

r"
"
g

Test String