Jordan Kasper | @jakerella
Often used for data validation
Test against pattern (true/false)
Find matching groups
(and possibly replace content)
Same language, engines.
For example: PHP native versus PCRE
POSIX (standard), BRE/ERE (Linux (grep)), Perl, java.util.regex, XRegExp (JS)
/the regex goes in here/
`the regex goes in here`
"the regex goes in here"
"/the regex goes in here/"
/foo/.test("foobar");
preg_match("/foo/", "foobar");
/foo/ =~ "foobar"
"foobar" =~ /foo/
/a/.test("JavaScript Rules"); // true
/z/.test("JavaScript Rules"); // false
true/false vs. matched groups
/a/.test("JavaScript Rules"); // true
"JavaScript Rules".match(/a/); // ["a"]
"JavaScript Rules".match(/z/); // null
"JavaScript Rules".match(/a/); // ["a"]
"JavaScript Rules".match(/r/); // ["r"]
// global
"JavaScript Rules".match(/r/g); // ["r"]
[ ], ?, +, *, { }
[^]
\ . ? * + - | [ ] ( ) { } ^ $
( | )
Creating a matched group adds processing time!
This differs from engine to engine!
"I like {{fav}} the most".replace(/{{fav}}/, "dogs");
"I like dogs the most"
"jordan@jordankasper.com"
.replace(/([a-z]+)@([a-z.]+)/i, "https://$2/users/$1");
"https://jordankasper.com/users/jordan"
^ and $
^ and $
Watch out for:
Jordan Kasper | @jakerella
They are not matches, but assertions.
/(the)(?=\sfat)/i
The fat cat sat on the mat
/(the)(?!\sfat)/i
The fat cat sat on the mat
Same idea, but looking backward instead of forward.
Not supported in all languages!
(notabley: JavaScript)
/(?<=the\s)([a-z]at)/i
The fat cat sat on the mat
We also have negative look behind with: (?<!)