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
/
^(?=.{3,20}$)(?![_.-])(?!.*[_.-]{2})[a-zA-Z0-9_-]+([^._-])$
/
^ asserts position at start of the string
Positive Lookahead
(?=.{3,20}$)
Assert that the Regex below matches
.
matches any character (except for line terminators)
{3,20} matches the previous token between 3 and 20 times, as many times as possible, giving back as needed (greedy)
$ asserts position at the end of the string
Negative Lookahead
(?![_.-])
Assert that the Regex below does not match
Match a single character present in the list below
[_.-]
_.
matches a single character in the list _. (case sensitive)
- matches the character - with index 4510 (2D16 or 558) literally (case sensitive)
This hyphen is treated literally, which might be confusing for others. Consider escaping it or placing at the start or end of the class!
Negative Lookahead
(?!.*[_.-]{2})
Assert that the Regex below does not match
.
matches any character (except for line terminators)
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
Match a single character present in the list below
[_.-]
{2} matches the previous token exactly 2 times
_.
matches a single character in the list _. (case sensitive)
- matches the character - with index 4510 (2D16 or 558) literally (case sensitive)
This hyphen is treated literally, which might be confusing for others. Consider escaping it or placing at the start or end of the class!
Match a single character present in the list below
[a-zA-Z0-9_-]
+ matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
a-z matches a single character in the range between a (index 97) and z (index 122) (case sensitive)
A-Z matches a single character in the range between A (index 65) and Z (index 90) (case sensitive)
0-9 matches a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)
_ matches the character _ with index 9510 (5F16 or 1378) literally (case sensitive)
- matches the character - with index 4510 (2D16 or 558) literally (case sensitive)
This hyphen is treated literally, which might be confusing for others. Consider escaping it or placing at the start or end of the class!
1st Capturing Group
([^._-])
Match a single character not present in the list below
[^._-]
._
matches a single character in the list ._ (case sensitive)
- matches the character - with index 4510 (2D16 or 558) literally (case sensitive)
This hyphen is treated literally, which might be confusing for others. Consider escaping it or placing at the start or end of the class!
$ asserts position at the end of the string
Your regular expression does not match the subject string.

Regular Expression
No Match

/
/

Test String