Regular Expressions are everywhere. This guide takes you through some of the most commonly found regex, how to read and write them into your codebase.
This guide will cover Javascript regex
Questions to ask yourself before designing regular expressions:
- Is the content I am looking for in a pattern or more dynamic?
- Anchors
- Quantifiers
- OR Operator
- Character Classes
- Flags
- Grouping and Capturing
- Bracket Expressions
- Greedy and Lazy Match
- Boundaries
- Back-references
- Look-ahead and Look-behind
Quantifiers define quantities and indicate numbers of characters or expressions to match. The characters used are:
n+ n* n? n{x} n{,x} n{x,y}
. Here are examples:
/ab+/.test('abbcdab') // matches "abb"
/bb*/.test('abbcdab') // matches "bb"
/b{2,}/.test('abbcdab') // matches "bb"
/a{1,3}/.test('bbcdaaab') // matches "aa"
Flag are also called modifiers because they modify the output of a regular expression. Flags can be used in any order or combination:
Flag | Description |
---|---|
i | Case insensitive: Sets matching to be case-insensitive |
g | Global Search: Search for a pattern throughout the input string. |
m | Multiline:Anchor meta character works on each line. |
Boundaries indicate the beginning and end of lines and words. The characters used are ^$\b\B
. Here are examples:
/^An/.test('An Apple) // matches "An"
/App$/.test('Mobile App') // matches "App"
/un\b/.test('Sun') // matches "un"
/\Bon/.test('Moon') // matches "on"
AKA. Assertions (which also include conditional expressions)
Note that the
?
character is also used as a quantifier
Characters | Example | Descriptions |
---|---|---|
x(?=y) |
/Atta(?=shah)/ |
Look-ahead assertion. Matches x only if it is followed by y . |
x(?!y) |
/\d+(?!\.)/ |
Negative look-ahead assertion. Matches x only if it is NOT followed by y . |
(?<=y)x |
/(?<=shah)Atta/ |
Look-behind assertion. Matches x only if it is preceeded by y . |
(?<!y)x |
/(?<!-)\d+/ |
Negative look-behind assertion. Matches x only if it is NOT preceeded by y . |
Gist created in September 2020 by Chris Maxwell. Check out my bio page here: https://withchristopher.github.io/csmportfolio/ Checkout my github here: https://github.com/withchristopher Follow me on Twitter here: https://twitter.com/withchristopher