Home » Blog » Learn to Regex – Cheatsheet

Learn to Regex – Cheatsheet

In this article, I am going to share some of the resources that you can use to learn Regex (Regular Expressions) easily.

Resources to learn regex :

Commands Usage (Coming Soon):

Wildcard Dot Character (.)

Find Letters, Numbers and Underscore Characters using (\w)

Find Characters Other Than Letters, Numbers and Underscores (\W)

Find Only Numeric Characters (\d)

Find Only Non-Numeric Characters – (\D)

Find Space Characters (\s)

Find Non-Space Characters – (\S)

Match if character is there or not there – (*)

Match if character can occur one or more times – (+)

Match if character is a optional character – (?)

Find for n no.of occurences of a character – {n}

Find character if it can occur at least n times – {n, }

Find character if it can occur for n or range-n times – {n, range-n}

Non-Capturing Grouping – (?:)

| – Pipe is used to specify that an expression can be in different expressions.

\ – Escape character is used before any special symbol to match them.

Selecting by Line Start – (^)

Selecting by End of Line – ($)

Positive Lookahead – (?=)

Negative Lookahead – (?!)

Positive Lookbehind – (?<=)

Negative Lookbehind – (?<!)

Flags

Flags change the output of the expression. That’s why flags are also called modifiers. Determines whether the typed expression treats text as separate lines, is case sensitive, or finds all matches. Continue to the next step to learn the flags.

\g – Global Flag – The global flag causes the expression to select all matches. If not used it will only select the first match.
\m – Multiline Flag – The multiline flag helps to handle each line seperately
\i – Case-Insensitive Flag – This flag checks the text for both lowercase or uppercase

Greedy Matching

In /.*r/ in ber beer beeer beeeer gives ber beer beeer beeeer

RegEx does a greedy match by default. This means that the matchmaking will be as long as possible. Check out the example below. It refers to any match that ends in r and can be any character preceded by it. But it does not stop at the first letter r.

Lazy Matching

In /.*?r/ in ber beer beeer beeeer gives ber

Lazy matchmaking, unlike greedy matching, stops at the first matching. For example, in the example below, add a ? after * to find the first match that ends with the letter r and is preceded by any character. It means that this match will stop at the first letter r.