Beginner's Guide to Regex
Tags: javascript, regex, beginners, webdev
Published: 2022-05-18 19:11:14

## Regex or Regexp ?

It stands for *Regular Expression*. It is a character matching mechanism. In other words, regular expressions are the pattern to match standalone character or a combination of characters in a string. It was coined in the beginning of 1950s, when the American mathematician Stephen Cole Kleene formalized the concept of a regular language. Most general-purpose programming languages support regex capabilities either natively or via libraries, including example Python, C, C++, Java, and JavaScript.

**How does it work ?**

There are the following rules a regex engine follows to find the match:

1. It reads the whole input string and attempts to match the characters against the instructions one at a time.
2. It reads the string from left to right
3. If a character matches according to the instruction that we have imposed, it returns true and goes for the next character to match. if a character doesn't match it returns false and goes for matching the next character from start. 
4.If all the instructions matched it returns success indicating regex matched successfully.

## Basic matching

A regular expression is just a pattern of characters that we use to perform a search in a text.
For example, the regular expression `the` means letter `t`, followed by the letter `h`, followed by the letter `e`.

<pre><code>"the" => The fat cat sat on <span style="color:red">the</span> mat.
</code></pre>

## Meta-characters ?

Meta-characters are reserved characters to set a specific rule for matching.
The meta characters are as follows:

- `^` : It specifies the starting of the string. This metacharacter helps us to match a string starting with a specific substring.

<pre><code>^The => <span style="color:red">The</span> car is parked in the garage.
</code></pre>

- `$` : Matches the end of the string. If a string ends with a specific character then we can use the `$` to find the match.

Wihtout `$`:
<pre><code>at\. => The fat c<span style="color:red">at.</span> s<span style="color:red">at.</span> on the m<span style="color:red">at.</span></code></pre>
With `$`:
<pre><code>at\.$ => The fat cat. sat. on the m<span style="color:red">at.</span></code></pre>

- `.` : It matches a single character without a line break. This is the simplest meta character. It helps us to match the next single character, if we put `.` after the matching pattern or the previous single character, if we put before the matching pattern.

<pre><code>.at => The <span style="color:red">fat</span> <span style="color:red">cat</span> <span style="color:red">sat</span> on the <span style="color:red">mat</span>.</code></pre>

<pre><code>ca. => The fat <span style="color:red">cat</span> sat on the mat.</code></pre>

- `[]` : Character Class. It matches any character written inside a square bracket. If we want to match a specific character then we can use character class and write a matching pattern between the square bracket.

<pre><code>[0-9] => <span style="color:red">3</span> fat cats sat on the mat.</code></pre>

- `[^]` : Neglected Character Class. It does not match any character written inside in a square bracket. it is similar to character class but in this case, we don't want to match specific characters we can use neglected character class. If caret (`^`) is available before a matching pattern wrapped inside the square bracket then expect the matching pattern it matches all other characters available in the string.

<pre><code>[^a-b] => <span style="color:red">3</span> fat cats sat on the mat.</code></pre>

- `*` : It is used with another rule like `[a-z]*`. It matches <u>zero or more than zero the occurrence</u> of preceding characters. If `*` is written after the matching pattern then it matches zero or more than zero repetition of the matching pattern.

<pre><code>[0-9] => <span style="color:red">5</span>25 fat cats sat on the mat.</code></pre>

<pre><code>[0-9]* => <span style="color:red">525</span> fat cats sat on the mat.</code></pre>

It is generally used with whitespace character (`\s`) when we want to match a substring followed by zero or more than zero whitespaces available.

<pre><code>The\s*fat => <span style="color:red">The fat</span> cat sat on the mat.</code></pre>

- `+` : This works the same as `*` works but instead of matching zero or more than zero occurrences, it matches <u>one or more than one occurrence</u> of preceding characters. If plus is written after the matching pattern then it matches one or more than one repetition of the matching pattern.

<pre><code>[0-9]+ => <span style="color:red">525</span> fat cats sat on the mat.</code></pre>

The difference ?
<pre><code>hel* => <span style="color:red">he</span>o.</code></pre>
<pre><code>hel+ => heo. //no match</code></pre>

- `?` : Makes the preceding symbol optional. This symbol matches zero or one instance of the preceding character.

<pre><code>[t]?he=> <span style="color:red">the</span> fat cat sat on <span style="color:red">the</span> mat <span style="color:red">he</span>.</code></pre>

- `{n, m}` : It specifies the range of the preceding string. In this case, the string should not be less than n characters and more than m characters.

<pre><code>[0-9]{2, 3}=> the value of pi is 3.<span style="color:red">141</span>5.</code></pre>

In this example, if we omit the second parameter (3) then it finds a match with 2 or more digits.

<pre><code>[0-9]{2,}=> the value of pi is 3.<span style="color:red">14159</span>.</code></pre>

If we omit the comma too then it finds a match with exactly 2 digits.

<pre><code>[0-9]{2}=> the value of pi is 3.<span style="color:red">14</span>1.</code></pre>

- `(xyz)` : Character Group. Matches substring written inside parentheses.

- `|` : Alternation. It is similar to the OR operator. 

<pre><code>(T|t)he|car => <span style="color:red">The car</span> is parked in <span style="color:red">the</span> garage.</code></pre>

- `\` : Escape. This allows you to match reserved characters [ ] ( ) { } . * + ? ^ $ \ |. For example, if we want to find `.` character then we need to write `\.` as for the rule.

## Assertions

Assertions include boundaries, which indicate the beginnings and endings of lines and words, and other patterns.

- **Lookahead Assertion:**

`x(?=y)` matches `x` if it is followed by `y`.

<pre><code>monica(?=\sgeller) => my name is <span style="color:red">monica</span> geller.</code></pre>

- **Negative Lookahead Assertion**

`x(?!y)` matches `x` if it is not followed by `y`.

<pre><code>geller(?!\sfamily) => monica geller belongs to the <span style="color:red">geller</span> family.</code></pre>

- **Look Behind Assertion**

`(?<=x)y` matches `y` if it is preceded by `x`

<pre><code>(?<=monica\s)geller=> monica <span style="color:red">geller</span> belongs to the geller family.</code></pre>


- **Negative Look Behind Assertion**

`(?<!x)y` matches `y` if it is not preceded by `x`

<pre><code>(?<!monica\s)geller=> monica geller belongs to the <span style="color:red">geller</span> family.</code></pre>

## Lazy vs Greedy matching

By default, a regex will perform a greedy match, which means the match will be as long as possible. We can use ? to match in a lazy way, which means the match should be as short as possible.

**Lazy Matching**

<pre><code>he.*l=> say <span style="color:red">hello to hell</span>.</code></pre>

**Greedy matching**

<pre><code>he.*?l=> say <span style="color:red">hell</span>o to <span style="color:red">hell</span>.</code></pre>

## Flags

Flags are also called modifiers because they modify the output of a regular expression. These flags can be used in any order or combination, and are an integral part of the RegExp.

- `i` : Case insensitive: Match will be case-insensitive.

- `g` : Global Search: Match all instances, not just the first.

- `m` : Multiline: Anchor meta characters work on each line.

## Regex in JavaScript

There are two ways to create a RegExp object: a literal notation and a constructor.

- The literal notation's parameters are enclosed between slashes and do not use quotation marks.
```javascript
\[0-9]\
```
- The constructor function's parameters are not enclosed between slashes but do use quotation marks.
```javascript
new RegExp('[0-9]')
```

These patterns are used with the `exec()` and `test()` methods of RegExp, and with the `match()`, `matchAll()`, `replace()`, `replaceAll()`, `search()`, and `split()` methods of String.

---

I hope this beginner's guide helps you to understand the basics of regex.

Practice regex with [Regex 101](https://regex101.com/)

---

---