TIL: My RegEx Journey, pt1
Like I said yesterday, I wanted to spend some time focusing on walking through some regex basics so that I can hopefully get them stuck in my head once and for all.
Today is going to be the first of a multi part journey (probably 3 days) of me trying to get something to stick.
What’s the point?
Regular expressions are a super efficient way of searching through strings. It allows for pattern matching to pull out pieces of text you’re interested in.
A regex consists of a query between two forward slashes, with optional flags following the trailing slash:
Flags can be used to modify the query, like telling it to find more than one match, look across multiple lines, etc.
The query itself can be written in a bunch of different ways which will be covered further down below. In the most basic example, if you were to put
dog inside of the query, you would be matching exactly on
.test() method. This will return back a
true/false whether or not the string has been matched.
The above will return back true, as
is a is found within the
If you want to match off of more than just one word/set of characters, you can use an or
| to tell the regex to look for multiple matches:
By default, all queries are case sensitive. That’s to say that a query of
dog will not match a string with
Dog in it.
This can be fixed by using a case insensitive query flag,
If you actually want to extract the value that matches the query, you can use the
.match() is used on the string rather than the regex itself:
Matching More Than First Match
By default only the first match will be found before the string is no longer scanned.
To force the full string to be looked at for multiple matches, the
g flag must be included.