<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Regex - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Regex - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 28 May 2026 04:42:25 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/regex/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Regular Expressions (RegEx) in JavaScript – A Handbook for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ Regular expressions, also known as regex, are powerful tools for pattern matching and text manipulation. Whether you're validating user input, extracting data from strings, or performing advanced text processing tasks, understanding regex is essentia... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/regex-in-javascript/</link>
                <guid isPermaLink="false">66c72195e39cd88fc3e1ccfe</guid>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Regex ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Samyak Jain ]]>
                </dc:creator>
                <pubDate>Tue, 27 Feb 2024 20:17:37 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/Regular-Expressions-in-JavaScript-Cover-2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Regular expressions, also known as regex, are powerful tools for pattern matching and text manipulation. Whether you're validating user input, extracting data from strings, or performing advanced text processing tasks, understanding regex is essential for developers.</p>
<p>This comprehensive guide will walk you through the fundamentals of regular expressions in JavaScript, including how to create and use them, their special characters, flags, and practical examples. </p>
<h3 id="heading-prerequisites">Prerequisites:</h3>
<p>While this tutorial is designed to be beginner-friendly, having a basic understanding of JavaScript fundamentals will be beneficial. Familiarity with variables, data types, functions, and string manipulation in JavaScript will help you grasp the concepts covered.</p>
<h2 id="heading-table-of-contents">Table of Contents:</h2>
<ol>
<li><a class="post-section-overview" href="#heading-what-are-regex">What are Regex</a>?<br>– <a class="post-section-overview" href="#heading-how-to-write-regular-expression-patterns">How to Write Regular Expression Patterns</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-regular-expressions-in-javascript">How to Use Regular Expressions in JavaScript</a><br>– RegEx Methods in JavaScript<br>– <a class="post-section-overview" href="#heading-advanced-searching-with-flags">Advanced Searching with Flags</a></li>
<li><a class="post-section-overview" href="#heading-anchors-in-regex">Anchors in Regex</a><br>– <a class="post-section-overview" href="#heading-multiline-mode-of-anchors-and">Multiline Mode(m) of Anchors</a><br>– <a class="post-section-overview" href="#heading-word-boundaries-b">Word Boundaries (<code>\b</code>)</a></li>
<li><a class="post-section-overview" href="#heading-quantifiers-in-regex">Quantifiers in Regex</a><br>– <a class="post-section-overview" href="#heading-greedy-quantifiers">Greedy Quantifiers</a><br>– [Non Greedy Quantifiers (Lazy Mode)](#Non Greedy Quantifiers (Lazy Mode))</li>
<li><a class="post-section-overview" href="#heading-sets-and-ranges-in-regex">Sets and Ranges in Regex</a><br>– <a class="post-section-overview" href="#heading-sets">Sets</a><br>– <a class="post-section-overview" href="#heading-ranges">Ranges</a><br>– <a class="post-section-overview" href="#heading-negating-excluding-ranges">Negating / Excluding Ranges</a><br>– <a class="post-section-overview" href="#heading-predefined-character-classes">Predefined Character Classes</a></li>
<li><a class="post-section-overview" href="#heading-special-characters-and-escaping-in-regex">Special Characters and Escaping in Regex</a><br>– <a class="post-section-overview" href="#heading-metacharacters">Metacharacters</a><br>– <a class="post-section-overview" href="#heading-escape-special-characters">Escaping Special Characters</a></li>
<li><a class="post-section-overview" href="#heading-groupings-in-regex">Groupings in RegEx</a><br>– <a class="post-section-overview" href="#heading-capturing-groups">Capturing Groups</a><br>– <a class="post-section-overview" href="#heading-non-capturing-groups">Non-Capturing Groups</a><br>– <a class="post-section-overview" href="#heading-backreferences">Backreferences</a><br>– <a class="post-section-overview" href="#heading-regex-alternation">Regex Alternation</a></li>
<li><a class="post-section-overview" href="#heading-lookahead-and-lookbehind-in-regex">Lookahead and Lookbehind Assertions in Regex</a><br>– <a class="post-section-overview" href="#heading-lookahead">Lookahead (?=)</a><br>– <a class="post-section-overview" href="#heading-negative-lookaheads">Negative Lookahead (?!)</a><br>– <a class="post-section-overview" href="#heading-lookbehind">Lookbehind (?&lt;=)</a><br>– <a class="post-section-overview" href="#heading-negative-lookbehind">Negative Lookbehind (?&lt;!)</a></li>
<li><a class="post-section-overview" href="#heading-practical-examples-and-use-cases-of-regex">Practical Examples and Use Cases of Regex</a><br>– <a class="post-section-overview" href="#heading-password-strength-checking">Password Strength Checking</a><br>– <a class="post-section-overview" href="#heading-email-validation-function">Email Validation</a><br>– <a class="post-section-overview" href="#heading-phone-number-formatting-function">Phone Number Formatting</a></li>
<li><a class="post-section-overview" href="#heading-tips-and-best-practices-for-using-regular-expressions">RegEx Tips and Best Practices</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<h2 id="heading-what-are-regex">What Are Regex?</h2>
<p>A regular expression, often abbreviated as "regex," is a sequence of characters that define a search pattern. This pattern is used to find matches within strings, helping you identify specific text or patterns of characters, providing a powerful way to search, replace, and manipulate text.</p>
<p>In JavaScript, you can create regular expressions using either a literal notation or the <code>RegExp</code> constructor:</p>
<ul>
<li><strong>Using a Regular Expression Literal</strong>: This involves enclosing the pattern between slashes ("/").</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/pattern/</span>;

<span class="hljs-comment">// example</span>
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/ab+c/</span>;
</code></pre>
<ul>
<li><strong>Using the Constructor Function: <code>RegExp</code></strong> constructor. This allows runtime compilation of the regular expression and is useful when the pattern may change.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> re = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(<span class="hljs-string">"pattern"</span>);

<span class="hljs-comment">// example</span>
<span class="hljs-keyword">const</span> re = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(<span class="hljs-string">"ab+c"</span>);
</code></pre>
<p>Both methods produce the same result – it's a matter of preference which one you choose.</p>
<h3 id="heading-how-to-write-regular-expression-patterns">How to Write Regular Expression Patterns</h3>
<p>A regular expression pattern can consist of simple characters or a combination of simple and special characters. </p>
<ol>
<li><strong>Simple Pattern</strong>: They match exact character sequences. For example, the pattern <code>/abc/</code> matches the sequence "abc" in a string.</li>
<li><strong>Special Characters</strong>: They enhance pattern matching with capabilities like repetition or matching specific types of characters, allowing for more flexible and powerful pattern matching. For example, <code>*</code> matches zero or more occurrences of the preceding item. <code>/ab*c/</code> matches "ac", "abc", "abbc", and so on.</li>
</ol>
<h2 id="heading-how-to-use-regular-expressions-in-javascript">How to Use Regular Expressions in JavaScript</h2>
<p>You can use regular expressions with various methods available for both the <code>RegExp</code> and <code>String</code> objects in JavaScript. Some methods like <code>test()</code>, <code>exec()</code>, and others have this syntax:</p>
<pre><code class="lang-javascript">regex.methodname(string)

<span class="hljs-comment">// example</span>
regex.test(string)
</code></pre>
<p>While some methods like <code>match()</code>, <code>replace()</code>, and so on have this syntax:</p>
<pre><code class="lang-javascript">string.methodname(regex)

<span class="hljs-comment">// example</span>
string.replace(regex, replacement)
</code></pre>
<p>Here, <code>string</code> is the string and <code>regex</code> is a regular expression pattern.</p>
<p>Let's explore how these methods are used in practice.</p>
<p><strong>The <code>test()</code> Method</strong>: checks whether a particular string matches a specified pattern or regular expression. It returns <code>true</code> if the pattern is found in the string, otherwise, it returns <code>false</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> pattern = <span class="hljs-regexp">/hello/</span>;
<span class="hljs-keyword">let</span> str = <span class="hljs-string">"hello world"</span>;

<span class="hljs-keyword">let</span> result = pattern.test(str);
<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: true</span>
</code></pre>
<p><strong>The <code>exec()</code> Method</strong>: searches for a match of a pattern within a string. It returns an array containing details like the matched text, index of the match within the string, and the input string itself. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> pattern = <span class="hljs-regexp">/world/</span>;
<span class="hljs-keyword">let</span> str = <span class="hljs-string">"hello world"</span>;

<span class="hljs-keyword">let</span> result = pattern.exec(str);
<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: ["world", index: 6, input: "hello world"]</span>
</code></pre>
<p><strong>The <code>match()</code> Method</strong>: Searches for occurrences of a pattern within a string. It returns the first element matched. If has the global flag (<code>g</code>), it returns an array containing all matches found, or <code>null</code> if no matches are found.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">"The quick brown fox jumps over the lazy dog."</span>;
<span class="hljs-keyword">let</span> matches = str.match(<span class="hljs-regexp">/the/gi</span>);

<span class="hljs-built_in">console</span>.log(matches); <span class="hljs-comment">// Output: ["The", "the"]</span>
</code></pre>
<p><strong>The <code>matchAll()</code> Method</strong>: Returns an iterator of all results matching a regular expression against a string. Each element of the iterator is an array containing details about the match, including captured groups.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">"Hello world! This is a test string."</span>;
<span class="hljs-keyword">let</span> regex = <span class="hljs-regexp">/[a-zA-Z]+/g</span>;

<span class="hljs-keyword">let</span> matches = str.matchAll(regex);

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> match <span class="hljs-keyword">of</span> matches) {
    <span class="hljs-built_in">console</span>.log(match);
}
</code></pre>
<p>This method is useful when you need detailed information about all matches found in a string.</p>
<p><strong>The <code>search()</code> Method</strong>: Searches for a specified pattern within a string. It returns the index of the first occurrence of the pattern within the string, or <code>-1</code> if the pattern is not found.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">"The quick brown fox jumps over the lazy dog"</span>;
<span class="hljs-keyword">let</span> pattern = <span class="hljs-regexp">/brown/</span>;

<span class="hljs-keyword">let</span> result = str.search(pattern);
<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: 10</span>
</code></pre>
<p><strong>The <code>replace()</code> Method</strong>: Replaces the first occurrence of a specified pattern in a string with another substring or value. To replace all occurrences, you can use the global flag (<code>g</code>) in the regular expression.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">"Hello, World!"</span>;
<span class="hljs-keyword">let</span> newStr = str.replace(<span class="hljs-regexp">/o/g</span>, <span class="hljs-string">"0"</span>);

<span class="hljs-built_in">console</span>.log(newStr); <span class="hljs-comment">// Output: "Hell0, W0rld!"</span>
</code></pre>
<p><strong>The <code>replaceAll()</code> Method</strong>: Replaces all occurrences of a specified substring or pattern with a replacement string. It differs from <code>replace()</code> in that it replaces all occurrences by default, without the need for a global flag (<code>g</code>).</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">"apple,banana,apple,grape"</span>;
<span class="hljs-keyword">let</span> newStr = str.replaceAll(<span class="hljs-string">"apple"</span>, <span class="hljs-string">"orange"</span>);
<span class="hljs-built_in">console</span>.log(newStr); <span class="hljs-comment">// Output: "orange,banana,orange,grape"</span>
</code></pre>
<p>This method simplifies the process of replacing all occurrences of a substring within a string.</p>
<p><strong>The <code>split()</code> Method</strong>: Though not exclusively a RegEx method, <code>split()</code> can accept a RegEx pattern as its argument to split a string into an array of substrings based on the specified patterns or delimiters. For instance:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">"apple,banana,grape"</span>;
<span class="hljs-keyword">let</span> arr = str.split(<span class="hljs-regexp">/,/</span>);
<span class="hljs-built_in">console</span>.log(arr); <span class="hljs-comment">// Output: ["apple", "banana", "grape"]</span>
</code></pre>
<p>These methods offer different functionalities based on your needs. For example, if you only need to know whether a pattern is found in a string, <code>test()</code> or <code>search()</code> methods are efficient. If you require more information about matches, the <code>exec()</code> or <code>match()</code> methods are suitable.</p>
<h2 id="heading-advanced-searching-with-flags">Advanced Searching with Flags</h2>
<p>In JavaScript, regular expressions support pattern flags, which are optional parameters that modify the behavior of the pattern matching. </p>
<p>Let's delve into two common flags: the ignore flag (<code>i</code>) and the global flag (<code>g</code>).</p>
<h3 id="heading-the-ignore-flag-i">The Ignore Flag (<code>i</code>):</h3>
<p>The ignore flag (<code>i</code>) instructs the regular expression to ignore case sensitivity when searching for matches. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/hello/i</span>;
<span class="hljs-keyword">let</span> testString = <span class="hljs-string">"Hello, World!"</span>;
<span class="hljs-keyword">let</span> result = re.test(testString);

<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: true</span>
</code></pre>
<p>In this case, the regular expression <code>/hello/i</code> matches the string <code>"Hello"</code> despite differences in case because we used the ignore flag.</p>
<h3 id="heading-the-global-flag-g">The Global Flag (<code>g</code>):</h3>
<p>The global flag (<code>g</code>) allows the regular expression to find all matches within a string, rather than stopping after the first match. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/hi/g</span>;
<span class="hljs-keyword">let</span> testString = <span class="hljs-string">"hi there, hi again!"</span>;
<span class="hljs-keyword">let</span> result = testString.match(re);

<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: ["hi", "hi"]</span>
</code></pre>
<p>In this example, the regular expression <code>/hi/g</code> finds both occurrences of <code>"hi"</code> in the string <code>"hi there, hi again!"</code>.</p>
<h3 id="heading-combining-flags">Combining Flags</h3>
<p>You can combine flags to achieve specific matching behavior. For instance, using both the ignore flag (<code>i</code>) and the global flag (<code>g</code>) together allows for case-insensitive matching while finding all occurrences of the pattern.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/hi/gi</span>;
<span class="hljs-keyword">let</span> testString = <span class="hljs-string">"Hi there, HI again!"</span>;
<span class="hljs-keyword">let</span> result = testString.match(re);

<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: ["Hi", "HI"]</span>
</code></pre>
<p>Here, the regular expression <code>/hi/gi</code> matches both <code>"Hi"</code> and <code>"HI"</code> in the string <code>"Hi there, HI again!"</code>.</p>
<h3 id="heading-the-u-flag">The <code>u</code> Flag:</h3>
<p>Though not commonly used, the <code>u</code> flag handles Unicode characters, especially surrogate pairs, correctly. Surrogate pairs are used to represent characters outside the Basic Multilingual Plane (BMP) in UTF-16 encoding.</p>
<p><strong>Example:</strong> Let's consider a string containing emoji characters and try to match them using a regular expression without and with the <code>u</code> flag.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Without the u flag</span>
<span class="hljs-keyword">let</span> result1 = <span class="hljs-string">'Smile Please 😊'</span>.match(<span class="hljs-regexp">/[😒😊🙄]/</span>);
<span class="hljs-built_in">console</span>.log(result1); <span class="hljs-comment">// Output: ["�"]</span>

<span class="hljs-comment">// With the u flag</span>
<span class="hljs-keyword">let</span> result2 = <span class="hljs-string">'Smile Please 😊'</span>.match(<span class="hljs-regexp">/[😒😊🙄]/u</span>);
<span class="hljs-built_in">console</span>.log(result2); <span class="hljs-comment">// Output: ["😊"]</span>
</code></pre>
<p>Without the <code>u</code> flag, the regex fails to match the emoji correctly because they are represented as surrogate pairs in UTF-16 encoding. However, with the <code>u</code> flag, it correctly matches the emoji <code>'😊'</code>.</p>
<h2 id="heading-anchors-in-regex">Anchors in Regex</h2>
<p>Anchors are special characters in regex that do not represent actual characters but instead indicate positions within a string. There are two main anchors: <code>^</code> and <code>$</code>.</p>
<p><strong>The <code>^</code> Anchor</strong>: The <code>^</code> anchor matches the beginning of the text. Basically, it checks if a string starts with a specific character or pattern.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'Mountain'</span>;
<span class="hljs-built_in">console</span>.log(<span class="hljs-regexp">/^S/</span>.test(str)); <span class="hljs-comment">// Output: false</span>
</code></pre>
<p><strong>The <code>$</code> Anchor</strong>: The <code>$</code> anchor matches the end of the text. It checks if a string ends with a specific character or pattern.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'Ocean'</span>;
<span class="hljs-built_in">console</span>.log(<span class="hljs-regexp">/n$/</span>.test(str)); <span class="hljs-comment">// Output: true</span>
</code></pre>
<p>You may often use <code>^</code> and <code>$</code> together to check if a string fully matches a pattern.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> isValid = <span class="hljs-regexp">/^\d\d:\d\d$/</span>.test(<span class="hljs-string">'10:01'</span>);
<span class="hljs-built_in">console</span>.log(isValid); <span class="hljs-comment">// Output: true</span>
</code></pre>
<ul>
<li>In the code above, <code>^\d\d:\d\d$</code> ensures that the string contains exactly two digits, followed by a colon, and then exactly two more digits.</li>
</ul>
<h3 id="heading-multiline-mode-of-anchors-and">Multiline Mode of Anchors (<code>^</code> and <code>$</code>):</h3>
<p>By default, the <code>^</code> and <code>$</code> anchors in regular expressions operate in single-line mode, meaning they match the beginning and end of the entire string. But in some cases, you might want to match the beginning and end of individual lines within a multiline string. This is where the multiline mode, indicated by the <code>m</code> flag, comes into play.</p>
<p>Since single-line mode is the default, it only matches the first digit "1" at the beginning of the string.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">`1st line
2nd line
3rd line`</span>;

<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/^\d/g</span>; <span class="hljs-comment">// "^\d" matches the digit at the beginning of the string</span>
<span class="hljs-keyword">let</span> matches = str.match(re);

<span class="hljs-built_in">console</span>.log(matches); <span class="hljs-comment">// Output: ["1"]</span>
</code></pre>
<ul>
<li><strong>multiline mode(m)</strong>: <code>/^\d/gm</code> is the regex pattern with the <code>m</code> flag enabled. By utilizing the <code>m</code> flag, you can ensure that <code>^</code> and <code>$</code> match the beginning and end of individual lines within a multiline string, rather than just the entire string itself.</li>
</ul>
<p>As a result, it matches "1" from the first line, "2" from the second line, and "3" from the third line:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">`1st line
2nd line
3rd line`</span>;

<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/^\d/gm</span>;
<span class="hljs-keyword">let</span> matches = str.match(re);

<span class="hljs-built_in">console</span>.log(matches); <span class="hljs-comment">// Output: ["1", "2", "3"]</span>
</code></pre>
<p> This is particularly useful when working with text that contains multiple lines or line breaks.</p>
<h3 id="heading-word-boundaries-b">Word Boundaries (<code>\b</code>) :</h3>
<p>The <code>\b</code> is a special character in regular expressions called an anchor, just like <code>^</code> and <code>$</code>. It's used to match a position in the string where a word character (such as a letter, digit, or underscore) is not followed or preceded by another word character. For instance:</p>
<ul>
<li><code>\bword\b</code> matches the word "word" in the string, but not substrings like "wording" or "swordfish".</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> pattern = <span class="hljs-regexp">/\bword\b/</span>;
<span class="hljs-keyword">let</span> pattern2 = <span class="hljs-regexp">/word/</span>;
<span class="hljs-built_in">console</span>.log(pattern.test(<span class="hljs-string">"This is a word."</span>)); <span class="hljs-comment">// Output: true</span>
<span class="hljs-built_in">console</span>.log(pattern.test(<span class="hljs-string">"This is wording."</span>)); <span class="hljs-comment">// Output: false (doesn't match "wording")</span>
<span class="hljs-built_in">console</span>.log(pattern2.test(<span class="hljs-string">"This is wording"</span>)); <span class="hljs-comment">// Output: True</span>
</code></pre>
<p><code>/word/</code> matches the substring "word" anywhere within the string. It matches "word" in "This is wording." because it doesn't include any word boundary assertions.</p>
<p>Other examples can be:</p>
<ul>
<li><code>\b\d+\b</code> matches whole numbers in the string, but doesn't include non-numeric characters adjacent to the numbers.</li>
<li><code>^\bword\b$</code> matches a string that consists solely of the word "word".</li>
</ul>
<h2 id="heading-quantifiers-in-regex">Quantifiers in Regex</h2>
<p>In regex, quantifiers enable you to specify the quantity of characters or character classes you want to match within a string. They are symbols or characters that define how many instances of a character or group you're looking for.</p>
<h3 id="heading-exact-count-n">Exact Count <code>{n}</code>:</h3>
<p>The simplest quantifier is <code>{n}</code>, which specifies an exact count of characters or character classes you want to match. Let's say we have a string "Year: 2022" and we want to extract the year from it:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'Year: 2022'</span>;
<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/\d{4}/</span>; <span class="hljs-comment">// Matches a four-digit number ; basically concise &amp; better way to write \d\d\d\d</span>

<span class="hljs-keyword">let</span> result = str.match(re);

<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: ["2022"]</span>
</code></pre>
<h3 id="heading-the-range-nm">The Range <code>{n,m}</code>:</h3>
<p>The range quantifier <code>{n,m}</code> matches a character or character class from n to m times, inclusively. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">"The meeting is scheduled for 10:30 AM and ends at 2 PM"</span>;
<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/\d{2,4}/g</span>; <span class="hljs-comment">// Matches numbers with 2 to 4 digits</span>

<span class="hljs-keyword">let</span> result = str.match(re);
<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: [ '10', '30' ]</span>
</code></pre>
<h3 id="heading-n-and-shorthands"><code>{n,}</code> and Shorthands:</h3>
<p>The <code>{n,}</code> quantifier matches a character or character class at least n times. Additionally, there are shorthand notations for common quantifiers. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'The price of the item is $2500'</span>;
<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/\d{2,}/g</span>; <span class="hljs-comment">// Matches numbers with 2 or more digits</span>

<span class="hljs-keyword">let</span> result = str.match(re);
<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: ["2500"]</span>
</code></pre>
<h3 id="heading-shorthands">Shorthands: <code>+</code>, <code>?</code>, <code>*</code>:</h3>
<p>The quantifiers <code>+</code>, <code>?</code>, and <code>*</code> are shorthand notations for common use cases. Let's use the shorthand <code>+</code> to match one or more digits in a phone number:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> phone = <span class="hljs-string">"+1-(103)-777-0101"</span>;
<span class="hljs-keyword">let</span> result = phone.match(<span class="hljs-regexp">/\d+/g</span>); <span class="hljs-comment">// Matches one or more digits</span>

<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: ["1", "103", "777", "0101"]</span>
</code></pre>
<h3 id="heading-quantifiers-zero-or-one">Quantifiers: Zero or One (<code>?</code>):</h3>
<p>The quantifier <code>?</code> in regular expressions means zero or one occurrence of the preceding character or group. It's equivalent to {0,1}. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'The sky is blue in color, but the ocean is blue in colour'</span>;
<span class="hljs-keyword">let</span> result = str.match(<span class="hljs-regexp">/colou?r/g</span>); <span class="hljs-comment">// Matches "color" and "colour"</span>

<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: ["color", "colour"]</span>
</code></pre>
<p>In this example, the regular expression <code>/colou?r/g</code> matches both "color" and "colour" in the given string, allowing for zero or one occurrence of the letter "u".</p>
<h3 id="heading-quantifiers-zero-or-more">Quantifiers: Zero or More (<code>*</code>):</h3>
<p>The quantifier <code>*</code> in regular expressions means zero or more occurrences of the preceding character or group. It's equivalent to {0,}. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'Computer science is fascinating, but computational engineering is equally interesting'</span>;
<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/comput\w*/g</span>; <span class="hljs-comment">// Matches "computer" and "computational"</span>

<span class="hljs-keyword">let</span> results = str.match(re);

<span class="hljs-built_in">console</span>.log(results); <span class="hljs-comment">// Output: ["computer", "computational"]</span>
</code></pre>
<h3 id="heading-greedy-quantifiers">Greedy Quantifiers:</h3>
<p>In regular expressions, quantifiers determine how many times a particular element can occur in a match. </p>
<p>By default, quantifiers operate in what's called a "greedy" mode. This means they try to match as much of the preceding element as possible. For instance:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> regexp = <span class="hljs-regexp">/".+"/g</span>;
<span class="hljs-keyword">let</span> str = <span class="hljs-string">'The "Boy" and his "Friends" were here'</span>;
<span class="hljs-built_in">console</span>.log( str.match(regexp) ); <span class="hljs-comment">// "Boy" and his "Friends"</span>
</code></pre>
<p>Instead of finding two separate matches ("Boy" and "Friends"), it finds one match encompassing both ("Boy" and his "Friends").</p>
<h4 id="heading-understanding-greedy-search">Understanding Greedy Search</h4>
<p>To understand why the initial attempt failed, let's delve into how the regular expression engine conducts its search. </p>
<ol>
<li>The engine starts from the beginning of the string and finds the opening quote.</li>
<li>It proceeds to match characters following the opening quote. Since the pattern is <code>".+"</code>, where <code>.</code> matches any character and <code>+</code> quantifies it to match one or more times, the engine continues matching characters until it reaches the end of the string.</li>
<li>The engine then backtracks to find the end quote <code>"</code> that would complete the match. It starts by assuming the maximum possible characters matched by <code>".+"</code> and gradually reduces the number of characters until it finds a valid match.</li>
<li>Eventually, the engine finds a match encompassing the entire substring "Boy" and his "Friends".</li>
</ol>
<p>This behavior of greedily matching as many characters as possible is the default mode of quantifiers in regular expressions and doesn't always yield the desired results. You can see this in the example where it results in a single match instead of multiple separate matches for quoted strings.</p>
<h3 id="heading-non-greedy-quantifiers-lazy-mode">Non Greedy Quantifiers (Lazy Mode):</h3>
<p>To address the limitations of greedy mode, regular expressions also support a lazy mode for quantifiers. In lazy mode, quantified characters are repeated the minimal number of times necessary to satisfy the pattern.</p>
<p>We can enable the lazy mode by appending a question mark <code>?</code> after the quantifier. For example, <code>*?</code> or <code>+?</code> denotes lazy repetition.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> regexp = <span class="hljs-regexp">/".+?"/g</span>;
<span class="hljs-keyword">let</span> str = <span class="hljs-string">'The "Boy" and his "Friends" were here'</span>;
<span class="hljs-built_in">console</span>.log( str.match(regexp) ); <span class="hljs-comment">// "Boy" "Friends"</span>
</code></pre>
<p>In this example, the lazy quantifier <code>".+?"</code> ensures that each quoted string is matched separately by minimizing the number of characters matched between the opening and closing quotes.</p>
<p>Let's trace the search process step by step to understand how the lazy quantifier works:</p>
<ul>
<li>The engine starts from the beginning of string and finds the opening quote.</li>
<li>Instead of greedily matching all characters until the end of the string, the lazy quantifier <code>".+?"</code> matches only the characters necessary to satisfy the pattern. It stops as soon as it encounters the closing quote <code>"</code>.</li>
<li>The engine repeats this process for each quoted string in the text, resulting in separate matches for "Boy" and "Friends".</li>
</ul>
<h2 id="heading-sets-and-ranges-in-regex">Sets and Ranges in Regex</h2>
<p>In regular expressions, you use sets and ranges to match specific characters or a range of characters within a given pattern.</p>
<h3 id="heading-sets">Sets:</h3>
<p>A set is defined using square brackets <code>[...]</code>. It allows you to match any character within the set. For example, <code>[aeiou]</code> matches any of the vowels 'a', 'e', 'i', 'o', or 'u'.</p>
<p><strong>Example:</strong> Suppose we have a string <code>'The quick brown fox jumps over the lazy dog.'</code>. To match all vowels in this string, we can use the regular expression <code>/[aeiou]/g</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'The quick brown fox jumps over the lazy dog.'</span>;
<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/[aeiou]/g</span>;
<span class="hljs-keyword">let</span> results = str.match(re);

<span class="hljs-built_in">console</span>.log(results); <span class="hljs-comment">// Output: ['e', 'u', 'i', 'o', 'o', 'u', 'o', 'e', 'e', 'a', 'o']</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'The cat chased the rats in the backyard'</span>;;
<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/[cr]at/g</span>;
<span class="hljs-keyword">let</span> results = str.match(re);

<span class="hljs-built_in">console</span>.log(results); <span class="hljs-comment">// Output: ['cats', 'rats']</span>
</code></pre>
<p>Here, the RegEx <code>[cr]at</code> matches words that start with either 'c', or 'r' and are followed by 'at'.</p>
<h3 id="heading-ranges">Ranges:</h3>
<p>Ranges allow you to specify a range of characters within a set. For example, <code>[a-z]</code> matches any lowercase letter from 'a' to 'z', and <code>[0-9]</code> matches any digit from '0' to '9'. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'Hello World!'</span>;
<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/[a-z]/g</span>;
<span class="hljs-keyword">let</span> results = str.match(re);

<span class="hljs-built_in">console</span>.log(results); <span class="hljs-comment">// Output: ['e', 'l', 'l', 'o', 'o', 'r', 'l', 'd']</span>
</code></pre>
<h3 id="heading-negating-excluding-ranges">Negating / Excluding Ranges:</h3>
<p>To exclude certain characters from a set, you can use the <code>^</code> symbol inside the square brackets. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'The price is $19.99'</span>;
<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/[^0-9]/g</span>;
<span class="hljs-keyword">let</span> results = str.match(re);

<span class="hljs-built_in">console</span>.log(results); <span class="hljs-comment">// Output: ['T', 'h', 'e', ' ', 'p', 'r', 'i', 'c', 'e', ' ', 'i', 's', ' ', '$', '.']</span>
</code></pre>
<p>Similarly <code>[^a-z]</code> will match any character that is not a lowercase letter:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'The price is $19.99'</span>;
<span class="hljs-keyword">let</span> results2 = str.match(<span class="hljs-regexp">/[^a-z]/g</span>);

<span class="hljs-built_in">console</span>.log(results2); <span class="hljs-comment">// Output: ['T', ' ', ' ', ' ', '$', '1', '9', '.', '9', '9']</span>
</code></pre>
<h3 id="heading-predefined-character-classes">Predefined Character Classes:</h3>
<p>Some character classes have predefined shorthand notations for common ranges of characters. </p>
<p><strong><code>\d</code> class</strong>: It matches any digit character, equivalent to the range <code>[0-9]</code>. Example: </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> phone = <span class="hljs-string">'+1-(103)-777-0101'</span>;
<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/\d/g</span>;
<span class="hljs-keyword">let</span> numbers = phone.match(re);
<span class="hljs-keyword">let</span> phoneNo = numbers.join(<span class="hljs-string">''</span>);
<span class="hljs-built_in">console</span>.log(phoneNo); <span class="hljs-comment">// Output: 11037770101</span>
</code></pre>
<p>We used the <code>match()</code> and <code>join()</code> methods to format the phone number. This approach simplifies the process of formatting and cleaning up data, making it suitable for various text processing applications.</p>
<p>Similarly, <code>**\s**</code> matches a single whitespace character, including spaces, tabs, and newline characters, and <code>**\w**</code> matches any word character (alphanumeric character or underscore), equivalent to the range <code>[a-zA-Z0-9_]</code>.</p>
<p>Combining these classes allows for more flexible and precise pattern matching, enabling a wide range of text processing tasks. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'O2 is oxygen'</span>;
<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/\w\d/g</span>;
<span class="hljs-built_in">console</span>.log(str.match(re)); <span class="hljs-comment">// Output: ["O2"]</span>
</code></pre>
<p>These predefined character classes provide convenient shortcuts for commonly used character ranges.</p>
<p><strong>Inverse classes</strong>, denoted by uppercase letters (for example, <code>\D</code>), match any character not included in the corresponding lowercase class. This provides a convenient way to match characters outside specific sets, such as non-digit characters, non-whitespace characters, or non-word characters. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> phone = <span class="hljs-string">'+1-(103)-777-0101'</span>;
<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/\D/g</span>;
<span class="hljs-built_in">console</span>.log(phone.replace(re,<span class="hljs-string">''</span>)); <span class="hljs-comment">// Output: 11037770101</span>
</code></pre>
<h2 id="heading-special-characters-and-escaping-in-regex">Special Characters and Escaping in Regex</h2>
<h3 id="heading-metacharacters">Metacharacters:</h3>
<p>Metacharacters are characters that have special meanings in Regular Expressions and are used to construct patterns for matching text. </p>
<p>Anchors (<code>^</code> and <code>$</code>), Alternation(<code>|</code>), quantifiers (<code>+</code>, <code>?</code>, <code>{}</code>), and predefined character classes ( <code>\d</code>, <code>\w</code>, <code>\s</code>) are all considered metacharacters, each serving distinct purposes in pattern definition. We also have a few more, which we'll cover now.</p>
<p><strong>Dot (<code>.</code>)</strong> is a metacharacter with a special meaning. It's used to match any single character except newline characters (<code>\n</code>). It serves as a wildcard, allowing for flexible pattern matching when the exact character is unknown or irrelevant. </p>
<p>If you need the dot to match newline characters as well, you can use the <code>/s</code> flag in JavaScript, which enables the "single line" mode, making the dot match any character including newline characters. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> regex = <span class="hljs-regexp">/a.b/</span>; 

<span class="hljs-built_in">console</span>.log(regex.test(<span class="hljs-string">'acb'</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(regex.test(<span class="hljs-string">'aXb'</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(regex.test(<span class="hljs-string">'a\nb'</span>)); <span class="hljs-comment">// false (newline character not matched)</span>
<span class="hljs-built_in">console</span>.log(regex.test(<span class="hljs-string">'a\nb'</span>, <span class="hljs-string">'s'</span>)); <span class="hljs-comment">// true (with 's' flag, newline character matched)</span>
<span class="hljs-built_in">console</span>.log(regex.test(<span class="hljs-string">'ab'</span>)); <span class="hljs-comment">// false (missing character between 'a' and 'b')</span>
</code></pre>
<p>The dot (<code>.</code>) can be combined with other regex elements to form more complex patterns. For example, <code>/.at/</code> matches any three-character sequence ending with 'at', such as 'cat', 'bat', or 'hat'.</p>
<h3 id="heading-escape-special-characters">Escape Special Characters:</h3>
<p>Escaping special characters is essential when you want to search for or match these characters in input strings without invoking their special regex meanings. </p>
<p>To match a special character literally in a regex pattern, you need to escape it by preceding it with a backslash (). This tells the regex engine to treat the special character as a regular character. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> str = <span class="hljs-string">'This ^ symbol is called Caret '</span>;
<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/[\^]/g</span>;
<span class="hljs-keyword">let</span> results = str.match(re);

<span class="hljs-built_in">console</span>.log(results); <span class="hljs-comment">// Output: ['^']</span>
</code></pre>
<p>Fun fact: the <code>/</code> we use to escape metacharacters is itself a metacharacter and can be escaped with another backslash as <code>//</code>.</p>
<h2 id="heading-groupings-in-regex">Groupings in RegEx</h2>
<h3 id="heading-capturing-groups">Capturing Groups:</h3>
<p>In JavaScript regular expressions, capturing groups are used to extract specific parts of a matched string. Imagine you have a path like "resource/id", for instance, "posts/123". To match this path, you can use a regular expression like <code>/\w+\/\d+/</code>.</p>
<ul>
<li><code>\w+</code> matches one or more word characters.</li>
<li><code>\/</code> matches the forward slash <code>/</code>.</li>
<li><code>\d+</code> matches one or more digits.</li>
</ul>
<p>Let's say you have a path like "posts/123" and you want to capture the <code>id</code> part (123). We can use capturing groups for this.</p>
<p>To create a capturing group, you enclose the part of the regex pattern you want to capture in parentheses. For example, <code>(\d+)</code> captures one or more digits.</p>
<p>Here's how it works:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> path = <span class="hljs-string">'posts/123'</span>;
<span class="hljs-keyword">const</span> pattern = <span class="hljs-regexp">/\w+\/(\d+)/</span>;

<span class="hljs-keyword">const</span> match = path.match(pattern);
<span class="hljs-built_in">console</span>.log(match);
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">[ <span class="hljs-string">'posts/123'</span>, <span class="hljs-string">'123'</span>, index: 0, input: <span class="hljs-string">'posts/123'</span>, groups: undefined ]
</code></pre>
<p>Here, <code>'123'</code> is captured by the capturing group <code>(\d+)</code>.</p>
<p><strong>Using Multiple Capturing Groups</strong>: You can have multiple capturing groups in a regex pattern. For example, to capture both the resource (like "posts") and the id (like "123") from the path "posts/123", you can use <code>/(\w+)\/(\d+)/</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> path = <span class="hljs-string">'posts/123'</span>;
<span class="hljs-keyword">const</span> pattern = <span class="hljs-regexp">/(\w+)\/(\d+)/</span>;

<span class="hljs-keyword">const</span> match = path.match(pattern);
<span class="hljs-built_in">console</span>.log(match);
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">[<span class="hljs-string">'posts/123'</span>, <span class="hljs-string">'posts'</span>, <span class="hljs-string">'123'</span>, index: 0, input: <span class="hljs-string">'posts/123'</span>, groups: undefined]
</code></pre>
<p>Here, <code>'posts'</code> and <code>'</code>123<code>'</code> are captured by the two capturing groups <code>(\w+)</code> and <code>(\d+)</code> respectively.</p>
<p><strong>Named Capturing Groups</strong> allow you to assign names to capturing groups, which makes it easier to reference them later in your code.</p>
<p>The syntax for named capturing groups is <code>(?&lt;name&gt;rule)</code>, where:</p>
<ul>
<li><code>()</code> indicates a capturing group.</li>
<li><code>?&lt;name&gt;</code> specifies the name of the capturing group.</li>
<li><code>rule</code> is a rule in the pattern.</li>
</ul>
<p>For example, suppose we want to capture the resource (like "posts") and the id (like "123") from the path "posts/123" using named capturing groups.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> path = <span class="hljs-string">'posts/123'</span>;
<span class="hljs-keyword">const</span> pattern = <span class="hljs-regexp">/(?&lt;resource&gt;\w+)\/(?&lt;id&gt;\d+)/</span>;

<span class="hljs-keyword">const</span> match = path.match(pattern);
<span class="hljs-built_in">console</span>.log(match);
</code></pre>
<p>Output:</p>
<pre><code class="lang-javascript">[
  <span class="hljs-string">'posts/123'</span>,
  <span class="hljs-string">'posts'</span>,
  <span class="hljs-string">'123'</span>,
  <span class="hljs-attr">index</span>: <span class="hljs-number">0</span>,
  <span class="hljs-attr">input</span>: <span class="hljs-string">'posts/123'</span>,
  <span class="hljs-attr">groups</span>: [<span class="hljs-built_in">Object</span>: <span class="hljs-literal">null</span> prototype] { <span class="hljs-attr">resource</span>: <span class="hljs-string">'posts'</span>, <span class="hljs-attr">id</span>: <span class="hljs-string">'10'</span> }
]
</code></pre>
<p>Here, <code>resource</code> and <code>id</code> are the names assigned to the capturing groups. We can access them using <code>match.groups</code>.</p>
<p><strong>Another Example</strong>: Let's say we have a path like "posts/2022/02/18" and we want to capture the resource (like "posts"), year (like "2022"), month (like "02"), and day (like "18") using named capturing groups.</p>
<p>The regex pattern for this would be:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> path = <span class="hljs-string">'posts/2024/02/22'</span>;
<span class="hljs-keyword">const</span> pattern =
  <span class="hljs-regexp">/(?&lt;resource&gt;\w+)\/(?&lt;year&gt;\d{4})\/(?&lt;month&gt;\d{2})\/(?&lt;day&gt;\d{2})/</span>;

<span class="hljs-keyword">const</span> match = path.match(pattern);
<span class="hljs-built_in">console</span>.log(match.groups);
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">{resource: <span class="hljs-string">'posts'</span>, year: <span class="hljs-string">'2024'</span>, month: <span class="hljs-string">'02'</span>, day: <span class="hljs-string">'22'</span>}
</code></pre>
<p>Here, each part of the path is captured using named capturing groups, making it easy to access them by their respective names.</p>
<h3 id="heading-non-capturing-groups">Non-capturing groups:</h3>
<p>In regular expressions, non-capturing groups are used to group parts of a pattern together for applying quantifiers or alternation, without capturing the matched substring. </p>
<p>To create a non-capturing group, you add <code>?:</code> at the beginning of the parentheses. So, <code>/(?:\d)+/</code> is the non-capturing version of the previous example. The <code>?:</code> tells the regex engine not to capture the matched substring.</p>
<p>Let's see the difference between capturing and non-capturing groups with an example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// capturing group</span>
<span class="hljs-keyword">const</span> regexWithCapture = <span class="hljs-regexp">/(\d{2})\/(\d{2})\/(\d{4})/</span>;
<span class="hljs-keyword">const</span> matchWithCapture = regexWithCapture.exec(<span class="hljs-string">'02/26/2024'</span>);

<span class="hljs-built_in">console</span>.log(matchWithCapture); <span class="hljs-comment">// ["02/26/2024", "02", "26", "2024"]</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">// non-capturing group</span>
<span class="hljs-keyword">const</span> regexWithoutCapture = <span class="hljs-regexp">/(?:\d{2})\/(?:\d{2})\/(?:\d{4})/</span>;
<span class="hljs-keyword">const</span> matchWithoutCapture = regexWithoutCapture.exec(<span class="hljs-string">'02/26/2024'</span>);

<span class="hljs-built_in">console</span>.log(matchWithoutCapture); <span class="hljs-comment">// ["02/26/2024"]</span>
</code></pre>
<p>In summary, non-capturing groups <code>(?:pattern)</code> behave like regular capturing groups <code>()</code> in terms of matching patterns, but they don't store the matched text in memory for later retrieval. This makes them useful when you don't need to extract specific parts of the matched text.</p>
<h3 id="heading-backreferences">Backreferences:</h3>
<p>Backreferences enable you to refer to previously captured groups within a regular expression. Think of them as variables that store matched patterns. </p>
<p>In JavaScript, the syntax for a backreference is <code>\N</code>, where <code>N</code> is an integer representing the capturing group number.</p>
<p>For instance, consider a string with a duplicate word "Lion" and we want to remove the duplicate word to get <code>'Lion is the King'</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> s = <span class="hljs-string">'Lion Lion is the King'</span>;
</code></pre>
<ul>
<li>First, we match a word using <code>\w+\s+</code>.</li>
<li>Then, we create a capturing group to capture the word using <code>(\w+)\s+</code>.</li>
<li>Next, we use a backreference (<code>\1</code>) to reference the first capturing group.</li>
<li>Finally, we replace the entire match with the first capturing group using <code>String.replace()</code>.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> pattern = <span class="hljs-regexp">/(\w+)\s+\1/</span>;
<span class="hljs-keyword">const</span> result = s.replace(pattern, <span class="hljs-string">'$1'</span>);
<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: 'Lion is the King'</span>
</code></pre>
<h3 id="heading-regex-alternation">Regex Alternation:</h3>
<p>Regex alternation is a feature that allows you to match different patterns within a single regular expression. It works similarly to the logical OR operator. In regex, you use the pipe symbol <code>|</code> to denote alternation, where you can match either A or B.</p>
<pre><code>A | B <span class="hljs-comment">// This means you can match either pattern A or pattern B.</span>
</code></pre><p>Now, let's explore some practical applications of regex alternation:</p>
<p><strong>Matching Time String in the hh:mm Format</strong>: Suppose we want to match time strings in the format hh:mm, where hh represents hours and mm represents minutes. A basic regular expression to match this format would be <code>/\d{2}:\d{2}/</code>. </p>
<p>However, this basic pattern matches invalid times like "99:99". To ensure we match valid times (hours ranging from 00 to 23 and minutes ranging from 00 to 59), we need to refine our regex using alternation.</p>
<p>To match valid hours (00 to 23), we can use the following pattern:</p>
<ul>
<li><code>[01]\d</code> matches numbers from 00 to 19.</li>
<li><code>2[0-3]</code> matches numbers from 20 to 23.</li>
</ul>
<p>So, the pattern for hours becomes <code>[01]\d|2[0-3]</code>.</p>
<p>To match valid minutes (00 to 59), we can use the pattern <code>[0-5]\d</code>.</p>
<p>Now, we can combine the hour and minute patterns using alternation to get the final regex pattern:</p>
<p><code>/([01]\d|2[0-3]):[0-5]\d/g</code></p>
<p>In this pattern:</p>
<ul>
<li><code>([01]\d|2[0-3])</code> matches valid hours.</li>
<li><code>:</code> matches the colon.</li>
<li><code>[0-5]\d</code> matches valid minutes.</li>
</ul>
<p>This regex pattern ensures that we only match valid time strings in the <code>hh:mm</code> format. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> timeString = <span class="hljs-string">'07:23 33:71 21:17 25:81'</span>;
<span class="hljs-keyword">const</span> pattern = <span class="hljs-regexp">/([01]\d|2[0-3]):[0-5]\d/g</span>;
<span class="hljs-keyword">const</span> matches = timeString.match(pattern);

<span class="hljs-built_in">console</span>.log(matches);
</code></pre>
<p><strong>Expected Output</strong>:</p>
<pre><code>[<span class="hljs-string">'07:23'</span>, <span class="hljs-string">'21:17'</span>]
</code></pre><h2 id="heading-lookahead-and-lookbehind-in-regex">Lookahead and Lookbehind in Regex</h2>
<h3 id="heading-lookahead">Lookahead:</h3>
<p>Lookahead in regular expressions allows matching a pattern (X) only if it's followed by another specific pattern (Y). The syntax is <code>X(?=Y)</code>, where:</p>
<ul>
<li><strong>X</strong> is the pattern you want to match.</li>
<li><strong>(?=Y)</strong> is the lookahead assertion indicating that <code>X</code> should be followed by <code>Y</code>.</li>
</ul>
<p><strong>Example</strong>: Let's say we have a string describing various distances, and we want to identify numbers followed by the units "miles" but not "kilometers". We can use lookahead in a regex pattern:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> dist = <span class="hljs-string">"He ran 5 miles, but not 10 kilometers."</span>;

<span class="hljs-keyword">const</span> regex = <span class="hljs-regexp">/\d+(?=\s*miles)/g</span>;

<span class="hljs-built_in">console</span>.log(dist.match(regex)); <span class="hljs-comment">// Output: ["5"]</span>
</code></pre>
<p><strong>Multiple Lookaheads</strong>: It's possible to have multiple lookaheads in a regular expression using the syntax <code>X(?=Y)(?=Z)</code>. This allows us to impose multiple conditions for matching.</p>
<p><strong>Example:</strong> Let's say we want to match strings that contain both "foo" and "bar", but in any order:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> regex = <span class="hljs-regexp">/(?=.*foo)(?=.*bar)/</span>;

<span class="hljs-built_in">console</span>.log(regex.test(<span class="hljs-string">"foobar"</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(regex.test(<span class="hljs-string">"barfoo"</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(regex.test(<span class="hljs-string">"foo"</span>));    <span class="hljs-comment">// false</span>
<span class="hljs-built_in">console</span>.log(regex.test(<span class="hljs-string">"bar"</span>));    <span class="hljs-comment">// false</span>
</code></pre>
<h3 id="heading-negative-lookaheads">Negative Lookaheads:</h3>
<p>To negate a lookahead, use a negative lookahead with the syntax <code>(?!Y)</code>, where the regex engine matches X only if it is not followed by Y.</p>
<p><strong>Example</strong>: Suppose we want to match numbers but not if they are followed by "miles":</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> text = <span class="hljs-string">"He ran 5 miles, but not 10 kilometers."</span>;

<span class="hljs-keyword">const</span> regex = <span class="hljs-regexp">/\d+(?!\s*miles)/g</span>;

<span class="hljs-built_in">console</span>.log(text.match(regex)); <span class="hljs-comment">// Output: ["10"]</span>
</code></pre>
<h3 id="heading-lookbehind">Lookbehind:</h3>
<p>Lookbehinds provide a way to match patterns based on what precedes them, essentially matching an element if there is another specific element before it.</p>
<p><strong>Example</strong>: Suppose we have a string containing prices, and we want to match numbers preceded by the currency symbol "$" but not preceded by "€". We can use a lookbehind in a regex pattern</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> priceString = <span class="hljs-string">"The price is $100, but €200."</span>;

<span class="hljs-keyword">const</span> regex = <span class="hljs-regexp">/(?&lt;=\$)\d+/g</span>;

<span class="hljs-built_in">console</span>.log(priceString.match(regex)); <span class="hljs-comment">// Output: ["100"]</span>
</code></pre>
<p><strong>Explaination</strong>: <code>(?&lt;=\$)</code> matches an element if there is a literal string "$" before it. The backslash <code>\</code> is used to escape the special character "$", treating it as a literal character.</p>
<h3 id="heading-negative-lookbehind">Negative Lookbehind:</h3>
<p>Negative lookbehinds allow you to match a pattern only if it is not preceded by a specific pattern. This is useful for excluding certain patterns from matches based on what precedes them. </p>
<p>Example: Suppose we have a string containing various prices in different currencies, and we want to match the numbers not preceded by the currency symbol "$". We can use a negative lookbehind in a regex pattern:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> priceString = <span class="hljs-string">"The price is $50, but not €100."</span>;

<span class="hljs-keyword">const</span> regex = <span class="hljs-regexp">/(?&lt;!\$)\b\d+\b/g</span>;

<span class="hljs-built_in">console</span>.log(priceString.match(regex)); <span class="hljs-comment">// Output: ["100"]</span>
</code></pre>
<p><strong>Explanation:</strong> <code>(?&lt;!\$)</code> is the negative lookbehind syntax, which matches the following pattern only if it is not preceded by the literal string "$".</p>
<h2 id="heading-practical-examples-and-use-cases-of-regex">Practical Examples and Use Cases of Regex</h2>
<p>Now, Let's explore some practical examples of using regular expressions in JavaScript applications to solve common problems and perform text manipulation tasks.</p>
<h3 id="heading-password-strength-checking">Password Strength Checking:</h3>
<p>You can use regular expressions to enforce password strength requirements, such as minimum length and the presence of special characters.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">checkPasswordStrength</span>(<span class="hljs-params">password</span>) </span>{
    <span class="hljs-keyword">let</span> pattern = <span class="hljs-regexp">/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&amp;*]).{8,}$/</span>;
    <span class="hljs-keyword">return</span> pattern.test(password);
}

<span class="hljs-built_in">console</span>.log(checkPasswordStrength(<span class="hljs-string">"Passw0rd!"</span>));    <span class="hljs-comment">// Output: true</span>
<span class="hljs-built_in">console</span>.log(checkPasswordStrength(<span class="hljs-string">"weakpassword"</span>)); <span class="hljs-comment">// Output: false</span>
</code></pre>
<p>Here's what this pattern does:</p>
<ul>
<li><code>(?=.*\d)</code>: Requires at least one digit.</li>
<li><code>(?=.*[a-z])</code>: Requires at least one lowercase letter.</li>
<li><code>(?=.*[A-Z])</code>: Requires at least one uppercase letter.</li>
<li><code>(?=.*[!@#$%^&amp;*])</code>: Requires at least one special character.</li>
<li><code>.{8,}</code>: Requires a minimum length of 8 characters.</li>
</ul>
<h3 id="heading-email-validation-function">Email Validation Function:</h3>
<p>Email validation is crucial for ensuring data integrity and security in web applications. With regex methods, we can easily implement robust email validation mechanisms.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">validateEmail</span>(<span class="hljs-params">email</span>) </span>{
    <span class="hljs-keyword">const</span> emailRegex = <span class="hljs-regexp">/^[^\s@]+@[^\s@]+\.[^\s@]+$/</span>;
    <span class="hljs-keyword">return</span> emailRegex.test(email);
}

<span class="hljs-built_in">console</span>.log(validateEmail(<span class="hljs-string">"example@email.com"</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(validateEmail(<span class="hljs-string">"invalid-email"</span>));      <span class="hljs-comment">// false</span>
</code></pre>
<p>Here's what this pattern does:</p>
<ul>
<li><code>^</code>: Asserts the start of the string.</li>
<li><code>[^\s@]+</code>: Matches one or more characters that are not whitespace or '@'.</li>
<li><code>@</code>: Matches the '@' symbol.</li>
<li><code>[^\s@]+</code>: Matches one or more characters that are not whitespace or '@'.</li>
<li><code>\.</code>: Matches the '.' symbol (escaped because '.' has a special meaning in RegEx).</li>
<li><code>[^\s@]+</code>: Matches one or more characters that are not whitespace or '@'.</li>
<li><code>$</code>: Asserts the end of the string.</li>
</ul>
<h3 id="heading-phone-number-formatting-function">Phone Number Formatting Function:</h3>
<p>Phone number formatting enhances user experience and readability in applications that involve phone number input and display.  </p>
<p>By defining a regex pattern that matches phone number components, we can easily format phone numbers into a desired pattern using the <code>replace()</code> method.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">formatPhoneNumber</span>(<span class="hljs-params">phoneNumber</span>) </span>{
    <span class="hljs-keyword">const</span> phoneRegex = <span class="hljs-regexp">/(\d{3})(\d{3})(\d{4})/</span>;
    <span class="hljs-keyword">return</span> phoneNumber.replace(phoneRegex, <span class="hljs-string">"($1) $2-$3"</span>);
}

<span class="hljs-keyword">const</span> formattedNumber = formatPhoneNumber(<span class="hljs-string">"9876543210"</span>);
<span class="hljs-built_in">console</span>.log(formattedNumber); <span class="hljs-comment">// (987) 654-3210</span>
</code></pre>
<p>In the <code>replace()</code> method, <code>$1</code>, <code>$2</code>, and <code>$3</code> represent the captured groups in the RegEx pattern, corresponding to the three sets of digits in the phone number.</p>
<h2 id="heading-tips-and-best-practices-for-using-regular-expressions">Tips and Best Practices for Using Regular Expressions</h2>
<h4 id="heading-1-understand-regular-expression-syntax">1. Understand Regular Expression Syntax:</h4>
<p>Understand the syntax and metacharacters of regular expressions for effective usage.</p>
<h4 id="heading-2-test-regular-expressions">2. Test Regular Expressions:</h4>
<p>Regular expressions can sometimes behave unexpectedly due to complex patterns or special characters. Always test your regular expressions with different input strings to ensure they behave as expected in various scenarios.</p>
<h4 id="heading-3-optimize-performance">3. Optimize Performance:</h4>
<p>Consider optimizing your regular expressions for performance by simplifying patterns or using more efficient alternatives where possible.</p>
<h4 id="heading-4-use-built-in-methods">4. Use Built-in Methods:</h4>
<p>JavaScript provides built-in methods like <code>String.prototype.match()</code>, <code>String.prototype.replace()</code>, and <code>String.prototype.split()</code> for common string manipulation tasks. Evaluate whether these methods can accomplish your task without the need for regular expressions.</p>
<h4 id="heading-5-comment-your-regular-expressions">5. Comment Your Regular Expressions:</h4>
<p>Add comments within your regex using <code>(?#comment)</code> syntax to explain explain parts of complex patterns. Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> regex = <span class="hljs-regexp">/(\d{3})-(\d{3})-(\d{4})\s(?# Match a phone number in the format XXX-XXX-XXXX)/</span>;
</code></pre>
<h4 id="heading-6-break-down-complex-patterns">6. Break Down Complex Patterns:</h4>
<p>If your regular expression becomes too complex to understand or maintain, consider breaking it down into smaller, more manageable parts. Use variables to store individual components of the pattern and combine them as needed.</p>
<h4 id="heading-7-use-online-resources-and-keep-on-practicing">7. Use Online Resources and Keep on Practicing:</h4>
<p>There are several online resources and tools available for testing and learning regular expressions. Websites like <a target="_blank" href="https://regex101.com/">Regex101</a> and <a target="_blank" href="https://regexr.com/">RegExr</a> provide interactive platforms to test and debug regular expressions. Also leverage online tutorials and documentation to learn regex concepts.</p>
<p>The MDN Web Docs have a helpful guide to <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions">Regular Expressions here</a>. And here's a quick start guide to regular expressions in JavaScript: <a target="_blank" href="https://www.freecodecamp.org/news/a-quick-and-simple-guide-to-javascript-regular-expressions-48b46a68df29/">RegExp Tutorial</a>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Regular expressions are versatile tools for pattern matching and manipulation in JavaScript. </p>
<p>By understanding their methods, advanced features, and usage with flags, leveraging online resources and debugging tools, you can effectively learn and apply them in various scenarios, from simple pattern matching to complex text processing tasks.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ A Practical Guide to Regular Expressions – Learn RegEx with Real Life Examples ]]>
                </title>
                <description>
                    <![CDATA[ What are Regular Expressions? Regular expressions, also known as regex, work by defining patterns that you can use to search for certain characters or words inside strings. Once you define the pattern you want to use, you can make edits, delete certa... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/practical-regex-guide-with-real-life-examples/</link>
                <guid isPermaLink="false">66ba2e427787ec7052709309</guid>
                
                    <category>
                        <![CDATA[ Bash ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Linux ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Regex ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Regular Expressions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Scripting ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tasnim Ferdous ]]>
                </dc:creator>
                <pubDate>Tue, 01 Aug 2023 20:42:27 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/08/The-Most-concise-guide-with-real-life-examples.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <h2 id="heading-what-are-regular-expressions">What are Regular Expressions?</h2>
<p>Regular expressions, also known as regex, work by defining patterns that you can use to search for certain characters or words inside strings.</p>
<p>Once you define the pattern you want to use, you can make edits, delete certain characters or words, substitute one thing for another, extract relevant information from a file or any string that contains that particular pattern, and so on.</p>
<h3 id="heading-why-should-you-learn-regex">Why Should You Learn Regex?</h3>
<p>Regex let you to do text processing in a way that can save you a lot of time. It can also introduce some fun in the process.</p>
<p>Using regex can make locating information much easier. Once you find your target, you can batch edit/replate/delete or whatever processing you need to do.</p>
<p>Some practical examples of using regex are batch file renaming, parsing logs, validating forms, making mass edits in a codebase, and recursive search.</p>
<p>In this tutorial, we're going to cover regex basics with the help of this <a href="https://regexr.com/" target="_blank">site</a>. Later on, I will introduce some regex challenges that you'll solve using Python. I'll also show you how to use tools like <code>sed</code> and <code>grep</code> with regex.</p>
<p>Like many things in life, regular expressions are one of those things that you can only truly understand by doing. I encourage you to play around with regex as you are going through this article.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>

<ul>
<li><a class="post-section-overview" href="#regex-basics">Regex Basics</a><ul>
<li><a class="post-section-overview" href="#exact-match">Exact match</a></li>
<li><a class="post-section-overview" href="#character-set">Character set</a><ul>
<li><a class="post-section-overview" href="#match-ranges-in-regex">Match ranges in regex</a></li>
<li><a class="post-section-overview" href="#match-any-character-not-in-the-set">Match any character not in the set</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#character-classes">Character classes</a></li>
<li><a class="post-section-overview" href="#heading-quantifiers">Quantifiers</a></li>
<li><a class="post-section-overview" href="#capture-groups">Capture groups</a><ul>
<li><a class="post-section-overview" href="#how-to-use-logical-or-in-regex">How to use logical OR in regex</a></li>
<li><a class="post-section-overview" href="#how-to-reference-capture-groups">How to reference capture groups</a></li>
<li><a class="post-section-overview" href="#how-to-name-capture-groups">How to name capture groups</a></li>
</ul>
</li>
</ul>
</li>
<li><a class="post-section-overview" href="#how-to-use-regex-with-command-line-tools">How to use regex with command line tools</a><ul>
<li><a class="post-section-overview" href="#recursive-regex-search-with-grep">Recursive regex search with grep</a></li>
<li><a class="post-section-overview" href="#substitution-with-sed">Substitution with sed</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#lookarounds">Advanced Regex: Lookarounds</a><ul>
<li><a class="post-section-overview" href="#heading-lookbehinds">Lookbehinds</a></li>
<li><a class="post-section-overview" href="#heading-lookaheads">Lookaheads</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#practical-examples-of-regex">Practical Examples of Regex</a><ul>
<li><a class="post-section-overview" href="#logs-parsing">Logs parsing</a></li>
<li><a class="post-section-overview" href="#bulk-file-renaming">Bulk File Renaming</a></li>
<li><a class="post-section-overview" href="#email-validation">Email validation</a></li>
<li><a class="post-section-overview" href="#password-constraints">Password constraints</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#final-words">Final words</a></li>
</ul>

<p><a></a></p>
<h2 id="heading-regex-basics">Regex Basics</h2>
<p>A regular expression is nothing but a sequence of characters that match a pattern. Besides using literal characters (like 'abc'), there are some meta characters (*,+,? and so on) which have special purposes. There are also features like character classes which can help you simplify your regular expressions. </p>
<p>Before writing any regex, you'll need to learn about all the basic cases and edge cases for the pattern you are looking for. </p>
<p>For instance, if you want to match 'Hello World', do you want the line to start with 'Hello' or can it start with anything? Do you want exactly one space between 'Hello' and 'World' or there can be more? Can other characters come after 'World' or should the line end there? Do you care about case sensitivity? And so on.</p>
<p>These are the kind of questions you must have the answer to before you sit down to write your regex.</p>
<p><a></a></p>
<h3 id="heading-exact-match">Exact match</h3>
<p>The most basic form of regex involves matching a sequence of characters in a similar way as you can do with Ctrl-F in a text editor.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/exact_match.png" alt="exact_match" width="600" height="400" loading="lazy"></p>
<p>On the top you can see the number of matches, and on the bottom an explanation is provided for what the regex matches character by character.</p>
<p><a></a></p>
<h3 id="heading-character-set">Character set</h3>
<p>Regex character sets allow you to match any one character from a group of characters. The group is surrounded by square brackets []. </p>
<p>For example, <code>t[ah]i</code> matches "tai" and "thi". Here 't' and 'i' are fixed but between them can occur 'a' or 'h'.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/match_set.png" alt="match_set" width="600" height="400" loading="lazy"></p>
<p><a></a></p>
<h4 id="heading-match-ranges-in-regex">Match ranges in regex</h4>
<p>Sometimes you may want to match a group of characters which are sequential in nature, such as any uppercase English letter. But writing all 26 letters would be quite tedious. </p>
<p>Regex solves this issue with ranges. The "-" acts as a range operator. Some valid ranges are shown below:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Range</td><td>Matches</td></tr>
</thead>
<tbody>
<tr>
<td>[A-Z]</td><td>uppercase letters</td></tr>
<tr>
<td>[a-z]</td><td>lowercase letters</td></tr>
<tr>
<td>[0-9]</td><td>Any digit</td></tr>
</tbody>
</table>
</div><p>You can also specify partial ranges, such as <code>[b-e]</code> to match any of the letters 'bcde' or <code>[3-6]</code> to match any of the numbers '3456'.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/match_set_ranges-1.png" alt="match_set_ranges" width="600" height="400" loading="lazy"></p>
<p>You are not limited to specifying only one range inside a character set. You can use multiple ranges and also combine them with any other additional character(s). Here, <code>[3-6u-w;]</code> will match any of '3456uvw' or semicolon ';'.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/match_set_ranges_multi-1.png" alt="match_set_ranges_multi" width="600" height="400" loading="lazy"></p>
<p><a></a></p>
<h4 id="heading-match-any-character-not-in-the-set">Match any character not in the set</h4>
<p>If you prefix the set with a '^', the inverse operation will be performed. For example, <code>[^A-Z0-9]</code> will match anything except uppercase letters and digits.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/match_set_not.png" alt="match_set_not" width="600" height="400" loading="lazy"></p>
<p><a></a></p>
<h3 id="heading-character-classes">Character classes</h3>
<p>While writing regex, you'll need to match certain groups such as digits quite often and multiple times in the same expression as well. </p>
<p>So for example, how would you match a pattern like 'letter-digit-letter-digit'? </p>
<p>With what you've learned up until now, you can come up with <code>[a-zA-Z]-[0-9]-[a-zA-z]-[0-9]</code>. This works, but you can see how the expression can get quite messy as the pattern length gets bigger.</p>
<p>To make the expression simpler, classes have been assigned to well-defined character groups such as digits. The following table shows these classes and their equivalent expression with character sets:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Class</td><td>Matches</td><td>Equivalent expression</td></tr>
</thead>
<tbody>
<tr>
<td>.</td><td>anything except newline</td><td>[^\n\r]</td></tr>
<tr>
<td>\w</td><td>word character</td><td>[a-zA-Z0-9_]</td></tr>
<tr>
<td>\W</td><td>non-word character</td><td>[^\w]</td></tr>
<tr>
<td>\d</td><td>digits</td><td>[0-9]</td></tr>
<tr>
<td>\D</td><td>non-digits</td><td>[^\d]</td></tr>
<tr>
<td>\s</td><td>space, tab, newlines</td><td>[ \t\r\n\f]</td></tr>
<tr>
<td>\S</td><td>non whitespace characters</td><td>[^\s]</td></tr>
</tbody>
</table>
</div><p>Character classes are quite handy and make your expressions much cleaner. We will use them extensively throughout this tutorial, so you can use this table as a reference point and come back here if you forget any of the classes.</p>
<p>Most of the time, we won't care about all the positions in a pattern. The "." class saves us from writing all possible characters in a set. </p>
<p>For example, <code>t..</code> matches anything that starts with t and any two characters afterwards. This may remind you of the SQL <code>LIKE</code> operator which would use <code>t%%</code> to accomplish the same thing.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/match_any.png" alt="match_any" width="600" height="400" loading="lazy"></p>
<p><a></a></p>
<h3 id="heading-quantifiers">Quantifiers</h3>
<p>The word "pattern" and "repetition" go hand in hand. If you want to match a 3 digit number you can use <code>\d\d\d</code>. But what if you need to match 11 digits? You could write '\d' 11 times, but a general rule of thumb while writing regex or just doing any kind of programming is that if you find yourself repeating something more than twice, you are probably unaware of some feature. </p>
<p>In regex, you can use quantifiers for this purpose. To match 11 digits, you can simply write the expression <code>\d{11}</code>.</p>
<p>The table below lists the quantifiers you can use in regex:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Quantifier</td><td>Matches</td></tr>
</thead>
<tbody>
<tr>
<td>*</td><td>0 or more</td></tr>
<tr>
<td>?</td><td>0 or 1</td></tr>
<tr>
<td>+</td><td>1 or more</td></tr>
<tr>
<td>{n}</td><td>exactly n times</td></tr>
<tr>
<td>{n, }</td><td>n or more times</td></tr>
<tr>
<td>{n, m}</td><td>n to m times inclusive</td></tr>
</tbody>
</table>
</div><p>In this example, the expression <code>can\s+write</code> matches <code>can</code> followed by 1 or more whitespaces followed by <code>write</code>. But you can see 'canwrite' is not matched as <code>\s+</code> means at least one whitespace needs to be matched. This is useful when you are searching through text which is not trimmed.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/match_multi_whitespaces.png" alt="match_multi_whitespaces" width="600" height="400" loading="lazy"></p>
<p>Can you guess what <code>can\s?write</code> will match?</p>
<p><a></a></p>
<h3 id="heading-capture-groups">Capture groups</h3>
<p>Capture groups are sub-expressions enclosed in parentheses (). You can have any number of capture groups, and even nested capture groups.</p>
<p>The expression <code>(The ){2}</code> matches 'The ' twice. But without a capture group, the expression <code>The {2}</code> would match 'The' followed by 2 spaces, as the quantifier will be applied on the space character and not on 'The ' as a group.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/capture_this.png" alt="capture_this" width="600" height="400" loading="lazy"></p>
<p>You can match any pattern inside capture groups as you would with any valid regex. Here <code>(is\s+){2}</code> matches if it finds 'is' followed by 1 or more spaces twice.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/capture_is.png" alt="capture_is" width="600" height="400" loading="lazy"></p>
<p><a></a></p>
<h4 id="heading-how-to-use-logical-or-in-regex">How to use logical OR in regex</h4>
<p>You can use "|" to match multiple patterns. <code>This is (good|bad|sweet)</code> matches 'This is ' followed by any of 'good' or 'bad' or 'sweet'.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/or-1.png" alt="or" width="600" height="400" loading="lazy"></p>
<p>Again, you must understand the importance of capture groups here. Think about what the expression <code>This is good|bad|sweet</code> would match?</p>
<p> <img src="https://www.freecodecamp.org/news/content/images/2023/07/or_no_capture.png" alt="or_no_capture" width="600" height="400" loading="lazy"></p>
<p>With a capture group, <code>good|bad|sweet</code> is isolated from <code>This is</code>. But if it's not inside a capture group, the entire regex is only one group. So the expression <code>This is good|bad|sweet</code> will match if the string contains 'This is good' or 'bad' or 'sweet'.</p>
<p><a></a></p>
<h4 id="heading-how-to-reference-capture-groups">How to reference capture groups</h4>
<p>Capture groups can be referenced in the same expression or while performing replacements as you can see on the Replacement tab. </p>
<p>Most tools and languages allow you to reference the nth captured group with '\n'. In this site '$n' is used while referencing on replacement. The syntax for replacement will vary depending on the tools or language you're using. For JavaScript, for example, its '$n', while for Python its '\n'.</p>
<p>In the expression <code>(This) is \1 power</code>, 'This' is captured and then referenced with '\1', effectively matching <code>This is This power</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/refer_capture.png" alt="refer_capture" width="600" height="400" loading="lazy"></p>
<p><a></a></p>
<h4 id="heading-how-to-name-capture-groups">How to name capture groups</h4>
<p>You can name your capture groups with the syntax <code>(?&lt;name&gt;pattern)</code> and backreference them in the same expression with <code>\k&lt;name&gt;</code>. </p>
<p>On replacement, referencing is done by <code>$&lt;name&gt;</code>. This is the syntax for JavaScript and can vary among languages. You can learn about the differences <a href="https://www.regular-expressions.info/named.html" target="_blank">here</a>. Also note that this feature might not be available in some languages.</p>
<p>In the expression <code>(?&lt;lang&gt;[\w+]+) is the best but \k&lt;lang&gt; .*</code>, the pattern <code>[\w+]+</code> is captured with the name 'lang' and backreferenced with <code>\k&lt;lang&gt;</code>. This pattern will match any word character or '+' character 1 or more times. The <code>.*</code> at the end of the regex matches any character 0 or more times. And finally on replacement, the referencing is done by <code>$&lt;lang&gt;</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/named_capture-1.png" alt="named_capture" width="600" height="400" loading="lazy"></p>
<p><a></a></p>
<h2 id="heading-how-to-use-regex-with-command-line-tools">How to Use Regex with Command Line Tools</h2>
<p>There are good CLI tools available that let you perform regex from your terminal. These tools save you even more time as you can easily test different regex without writing code in some langauge and then compiling or interpreting it. </p>
<p>Some of the well-known tools are grep, sed, and awk. Let's look at a few examples to give you some ideas on how you can leverage these tools.</p>
<p><a></a></p>
<h3 id="heading-recursive-regex-search-with-grep">Recursive regex search with grep</h3>
<p>You can execute the power of regex through grep. Grep can search patterns in a file or perform recursive search.</p>
<p>If you are on Windows, you can install grep using winget. Run this command in powershell:</p>
<pre><code class="lang-powershell">winget install <span class="hljs-literal">-e</span> -<span class="hljs-literal">-id</span> GnuWin32.Grep
</code></pre>
<p>I will show you the solution to a challenge I created for a CTF competition at my university. </p>
<p>The file attached to the challenge is a <a href="https://github.com/renzhamin/regex-guide/blob/main/ripG.zip" target="_blank">zip file</a> that contains multiple levels of directories and a lot of files in it. The name of the competition was Coderush with flag format <code>coderush{flag is here}</code>. So you have to search for the pattern <code>coderush{.*}</code> which will match the flag format <code>coderush{any character here}</code>.</p>
<p>Unzip the file with <code>unzip ripG.zip</code> and cd into it with <code>cd ripG</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/huge_files.png" alt="huge_files" width="600" height="400" loading="lazy"></p>
<p>There are 358 directories and 8731 files. Instead of searching the pattern in the files one by one, you can employ grep like this:</p>
<pre><code class="lang-sh">grep --color -R <span class="hljs-string">"coderush{.*}"</span>
</code></pre>
<p>The "-R" flag enables recursive search.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/grep.png" alt="recursive search with grep" width="600" height="400" loading="lazy"></p>
<p>You can learn more about grep and its command line options <a href="https://www.freecodecamp.org/news/grep-command-in-linux-usage-options-and-syntax-examples/" target="_blank">here</a></p>
<p><a></a></p>
<h3 id="heading-substitution-with-sed">Substitution with sed</h3>
<p>You can use sed to perform insertion, deletion, substitution on text files by specifying a regex. If you are on windows, you can get sed from <a href="https://github.com/mbuilov/sed-windows" target="_blank">here</a>. Or if you use WSL, tools like grep and sed will already be available.</p>
<p>This is the most common usage of sed:</p>
<pre><code class="lang-sh">sed <span class="hljs-string">'s/pattern/replacement/g'</span> filename
<span class="hljs-built_in">echo</span> <span class="hljs-string">"<span class="hljs-variable">${text}</span>"</span> | sed <span class="hljs-string">'s/pattern/replacement/g'</span>
</code></pre>
<p>Here, the option "g" is specified to replace all occurrences.</p>
<p>Some other useful options are <code>-n</code> to suppress the default behaviour of printing all lines and using p instead of g to print only the lines which are affected by the regex.</p>
<p>Let's take a look at the content of <a href="https://github.com/renzhamin/regex-guide/blob/main/texts.txt" target="_blank">texts.txt</a>.</p>
<pre><code>Hello rand chars World <span class="hljs-number">56</span> rand chars
Henlo <span class="hljs-number">52</span> rand chars W0rld rand chars
GREP rand chars Henlo <span class="hljs-number">62</span> rand chars
Henlo <span class="hljs-number">10</span> rand chars Henlo rand chars
GREP rand chars Henlo <span class="hljs-number">45</span> rand chars
</code></pre><p>Our task is replacing <code>Henlo number</code> with <code>Hello number</code> only in the lines where "GREP" is present. So, we are searching for the pattern <code>Henlo ([0-9]+)</code> which will match 'Henlo ' followed by 1 or more digits and all the digits are captured. Then our replacement string will be <code>Hello \1</code> – the '\1' is referencing the capture group containing the digits.</p>
<p>One way to accomplish that would be using grep to grep the lines which have "GREP" present then perform the replacement with sed.</p>
<pre><code class="lang-sh">grep <span class="hljs-string">"GREP"</span> texts.txt | sed -En <span class="hljs-string">'s/Henlo ([0-9]+)/Hello \1/p'</span>
</code></pre>
<p>The "-E" option enables extended regex without which you would need to escape the parentheses.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/grep_sed.png" alt="grep_sed" width="600" height="400" loading="lazy"></p>
<p>Or you could just use sed. Use <code>/pattern/</code> to restrict substitution on only the lines where pattern is present.</p>
<pre><code class="lang-sh">sed -En <span class="hljs-string">'/GREP/ s/Henlo ([0-9]+)/Hello \1/p'</span> texts.txt
</code></pre>
<p><a></a></p>
<h2 id="heading-advanced-regex-lookarounds">Advanced Regex: Lookarounds</h2>
<p>Lookaheads and Lookbehinds (together known as lookarounds) are features of regex that allow you to check the existence of a pattern without including it in the match.</p>
<p>You can think of them as zero width assertions – they assert the existence of a pattern but do not consume any characters in the match. These are very powerful features, but they're also computationally expensive. So make sure you keep an eye on performance if you are using them often.</p>
<p><a></a></p>
<h3 id="heading-lookbehinds">Lookbehinds</h3>
<p>Let's say you want to match the word 'linux', but you have 2 conditions.</p>
<ol>
<li>The word 'GNU' must occur before 'linux' occurs. If a line contains 'linux' but doesn't have 'GNU' before it, we want to discard that line.</li>
<li>We want to match only <code>linux</code> and nothing else.</li>
</ol>
<p>We already know how to satisfy the 1st condition. <code>GNU.*</code> will match 'GNU' followed by any number of characters. Then finally we match the word <code>linux</code>. This will match all of <code>GNU-any-characters-linux</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/GNU_LINUX.png" alt="GNU_LINUX" width="600" height="400" loading="lazy"></p>
<p>But how do we prevent matching <code>GNU.*</code> while still maintaining the 1st condition?</p>
<p>That's where a positive lookbehind comes in. You can mark a capture group as a positive lookbehind by prefixing it with <code>?&lt;=</code>. In this example, the expression becomes <code>(?&lt;=GNU.*)linux</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/positive_lookbehind.png" alt="positive_lookbehind" width="600" height="400" loading="lazy"></p>
<p>Now only <code>linux</code> is matched and nothing else.</p>
<p>Note that the expressions <code>(?&lt;=GNU.*)linux</code> and <code>linux(?&lt;=GNU.*)</code> will behave exactly the same. In the 2nd expression, although <code>linux</code> is before the lookbehind, there is <code>.*</code> after 'GNU' which matches <code>linux</code>. This means it satisfies the lookbehind. </p>
<p>To make it simpler, think about the pattern without the lookbehind. The pattern <code>GNU.*</code> will match 'GNU' and anything after it, in our case matching <code>linux</code>.</p>
<p>Now we can derive a generalized statement that the expression <code>(?&lt;=C)X</code> will match the pattern X – only if pattern C came before X (and C must not be included in the match).</p>
<p>You can also reverse the 1st condition. Match lines that contains the word <code>linux</code> only if <code>GNU</code> never came before it. This is called a negative lookbehind. The prefix in this case is <code>?&lt;!</code>. The inverse of the previous expression would be <code>(?&lt;!GNU.*)linux</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/negative_lookbehind.png" alt="negative_lookbehind" width="600" height="400" loading="lazy"></p>
<p><a></a></p>
<h3 id="heading-lookaheads">Lookaheads</h3>
<p>Lookaheads are also assertions like lookbehinds, as you saw in the previous example. The only difference is that lookbehinds make an assertion before and lookaheads makes assertion after.</p>
<p>Let's say you have these two conditions:</p>
<ol>
<li>Match <code>Hello</code> only if <code>World</code> comes somewhere after it.</li>
<li>Match only Hello and nothing else.</li>
</ol>
<p>The prefix for a positive lookahead is <code>?=</code>. The expression <code>Hello(?=.*World)</code> will meet both conditions. This is similar to <code>Hello.*World</code> except that only <code>Hello</code> will be matched whereas <code>Hello.*World</code> will match 'Hello', 'World' and anything in between.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/postive_lookahead-1.png" alt="postive_lookahead" width="600" height="400" loading="lazy"></p>
<p>Similar to the example in a positive lookbehind, the expressions <code>Hello(?=.*World)</code> and <code>(?=.*World)Hello</code> are equivalent. Because the <code>.*</code> before 'World' matches <code>Hello</code>, satisfying the 1st condition.</p>
<p>A negative lookahead is just the complement of a negative lookbehind. You can use it by prefixing it with <code>?!</code>. <code>(?!World)Hello</code> will match <code>Hello</code> only if there is no <code>World</code> anywhere after it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/negative_lookahead.png" alt="negative_lookahead" width="600" height="400" loading="lazy"></p>
<p>Here is a summary of the syntax for lookarounds when you want to match the pattern X with assertion C.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Operation</td><td>RegEx</td></tr>
</thead>
<tbody>
<tr>
<td>positive lookahead</td><td><code>(?=C)X</code></td></tr>
<tr>
<td>negative lookahead</td><td><code>(?!C)X</code></td></tr>
<tr>
<td>positive lookbehind</td><td><code>(?&lt;=C)X</code></td></tr>
<tr>
<td>negative lookbehind</td><td><code>(?&lt;!C)X</code></td></tr>
</tbody>
</table>
</div><p><a></a></p>
<h2 id="heading-practical-examples-of-regex">Practical Examples of Regex</h2>
<p><a></a></p>
<h3 id="heading-logs-parsing">Logs parsing</h3>
<p>In this <a href="https://github.com/renzhamin/regex-guide/blob/main/log_train.txt" target="_blank">log file</a>, these are the lines which we care about:</p>
<pre><code>[<span class="hljs-number">1</span>/<span class="hljs-number">10000</span>] Train loss: <span class="hljs-number">11.30368</span>, Valid loss: <span class="hljs-number">8.95446</span>, <span class="hljs-attr">Elapsed_time</span>: <span class="hljs-number">7.58941</span>
[<span class="hljs-number">500</span>/<span class="hljs-number">10000</span>] Train loss: <span class="hljs-number">0.96180</span>, Valid loss: <span class="hljs-number">0.20098</span>, <span class="hljs-attr">Elapsed_time</span>: <span class="hljs-number">82.48651</span>
[<span class="hljs-number">1000</span>/<span class="hljs-number">10000</span>] Train loss: <span class="hljs-number">0.04051</span>, Valid loss: <span class="hljs-number">0.11927</span>, <span class="hljs-attr">Elapsed_time</span>: <span class="hljs-number">156.86243</span>
</code></pre><p>Our task is to extract the training loss and validation loss for purposes such as plotting loss over the epochs. We need to extract the training loss values like <code>11.30368, 0.96180, 0.04051</code> and put them in an array.</p>
<p>All the relevant values are prefixed with '<code>Train loss:</code>', so we can use this in our regex as it is. To match the float numbers we have to match some digits followed by a "<code>.</code>" and then followed by more digits. You can do this with <code>\d+\.\d+</code>. Because we want to keep track of these numbers, they should be inside a capture group.</p>
<p>As "." has special purpose in regex, when you want to match a "." character you have to escape it with a backslash. This is applicable for all characters with a special purpose. But you dont have to escape it inside a character set.</p>
<p>Putting it altogether, the expression for extracting training loss is <code>Train loss: (\d+\.\d+)</code>. We can use the same logic to extract validation loss with <code>Valid loss: (\d+\.\d+)</code>.</p>
<p>Here is one way to extract this information using Python:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> re

f = open(<span class="hljs-string">"log_train.txt"</span>, <span class="hljs-string">"r"</span>).read()

train_loss = re.findall(<span class="hljs-string">r'Train loss: (\d+\.\d+)'</span>, f)
valid_loss = re.findall(<span class="hljs-string">r'Valid loss: (\d+\.\d+)'</span>, f)

train_loss = [float(i) <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> train_loss]
valid_loss = [float(i) <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> valid_loss]

print(<span class="hljs-string">"train_loss ="</span>, train_loss)
print(<span class="hljs-string">""</span>)
print(<span class="hljs-string">"valid_loss ="</span>, valid_loss)
</code></pre>
<p>When there is one capture group, <code>re.findall</code> searches all the lines and returns the values inside the capture group in a list. </p>
<p>Any regex function only return strings, so the values are converted to floats and printed out. Then you can directly use them in another Python script as a list of floats.</p>
<p>This is the result:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/extract_loss.png" alt="extract_loss" width="600" height="400" loading="lazy"></p>
<p>You could also use sed, save the output in train_losses.txt, and read from the file. First we use '/Train/' to target only the lines with 'Train' present then we are applying the same regex as before.</p>
<pre><code class="lang-sh">sed -En <span class="hljs-string">'/Train/ s/.*Train loss: ([0-9]+\.[0-9]+).*/\1/p'</span> log_train.txt | tee train_losses.txt
</code></pre>
<p>".*" is added at the start and end so that sed matches the contents of all the relevant lines. Then the entire line is replaced by the value of the capture group. The <code>tee</code> command is used to redirect the output of sed into train_losses.txt while also printing the contents in the terminal.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/extract_loss_sed.png" alt="extract_loss_sed" width="600" height="400" loading="lazy"></p>
<p>Take a moment to think about what would you need to extract the epochs. You have to extract 500 from [500/10000] for all such lines. The array should look like [1, 500, 1000, 1500, ...]. You can follow the same approach as we used for the previous example. </p>
<p>Note that if you want to match "<code>[</code>" or "<code>]</code>", you have to escape it. The answer is given <a target="_blank" href="https://github.com/renzhamin/regex-guide/blob/main/extract_epochs_array.py">here</a>.</p>
<p><a></a></p>
<h3 id="heading-bulk-file-renaming">Bulk File Renaming</h3>
<p>You have these <a href="https://github.com/renzhamin/regex-guide/tree/main/bulk-rename" target="_blank">files</a> with some random values as prefixes. You have to rename all files as 1.mp4, 2.mp4 and so on.
This is how the files were generated.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/create_files.png" alt="create_files" width="600" height="400" loading="lazy"></p>
<p>This is a common scenario where you have a list of files which have their sequence number in the name but there are also some other characters that you don't want.</p>
<p>The pattern has to match anything up to Episode then an underscore and then the number and .mp4 at the end. </p>
<p>The relevant value is the number before '.mp4' which we will put inside a capture group. <code>.*Episode_</code> will match everything up to the number. Then we can capture the number with <code>([0-9]+)</code> and also match .mp4 with <code>\.mp4</code>. </p>
<p>So the final regex is <code>.*Episode_([0-9]+)\.mp4</code>. As we want to keep the <code>.mp4</code> the replacement string will be <code>\1.mp4</code>.</p>
<p>This is one way to solve it using sed.</p>
<pre><code class="lang-sh"><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> *.mp4; <span class="hljs-keyword">do</span>
    newname=$(<span class="hljs-built_in">echo</span> <span class="hljs-variable">$i</span> | sed -En <span class="hljs-string">'s/.*Episode_([0-9]+)\.mp4/\1.mp4/p'</span>)
    mv <span class="hljs-variable">$i</span> <span class="hljs-variable">$newname</span>
<span class="hljs-keyword">done</span>;ls
</code></pre>
<p>First the new name is saved in a variable and then the mv command is used to rename the file.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/bulk_rename.png" alt="bulk_rename" width="600" height="400" loading="lazy"></p>
<p>Could we have just used <code>.*</code> in place of <code>.*Episode_</code> ? In this example, yes. But there might be filenames such as <code>Steins_Gate0.mp4</code> where the <code>0</code> is part of the movie name and you didn't really want to rename this file so its always better to be as specific as possible.</p>
<p>What if some files were named as "Random_Episode6.mp4"? The difference being, there is no underscore after Episode. What change will you need to make?</p>
<p>The answer is that you'll need to add a "?" after the "_" to make it optional. The regex will be <code>.*Episode_?([0-9]+)\.mp4</code>.</p>
<p><a></a></p>
<h3 id="heading-email-validation">Email validation</h3>
<p>There are all sorts of complicated regex for validating email.</p>
<p>Here is a simple one: <code>^[^@ ]+@[^@.]+\.\w+$</code>. It matches the format <code>A@B.C</code></p>
<p>The table below breaks down this pattern into smaller pieces:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Pattern</td><td>Matches</td></tr>
</thead>
<tbody>
<tr>
<td><code>^</code></td><td>start of line</td></tr>
<tr>
<td><code>[^@ ]+</code></td><td>anything except "@" and space character</td></tr>
<tr>
<td><code>@[^@.]+</code></td><td>@ followed by anything except "@" and "." characters</td></tr>
<tr>
<td><code>\.\w+</code></td><td>"." followed by word characters</td></tr>
<tr>
<td><code>$</code></td><td>end of line</td></tr>
</tbody>
</table>
</div><p><img src="https://www.freecodecamp.org/news/content/images/2023/07/email_validation.png" alt="email_validation" width="600" height="400" loading="lazy"></p>
<p>In the regexr site, you can enable the multline flag from the Flags tab in the upper right corner. The 'gm' at the end indicates that the multiline flag is enabled.</p>
<p>We can see that line 2,3,5,6 didn't match. Can you find out the reason and which part of the regex is responsible for disqualifying it?</p>
<p>The answer is given <a href="https://github.com/renzhamin/regex-guide/blob/main/email_validation.md" target="_blank">here</a></p>
<p><a></a></p>
<h3 id="heading-password-constraints">Password constraints</h3>
<p>You can also use regex to impose constraints. Here we will uncover the power of positive lookaheads. </p>
<p>Lets say we want to accept a string only if there is a digit in it. You already know how to find a digit with the '\d' class. To accomplish that, we can use <code>[^\d]*\d</code>. This will match any non-digit character 0 or more times and then match a digit. </p>
<p>We can also use the expression <code>.*\d</code> to match one digit. So if there is no digit in the string then the lookahead will fail and the none of the characters of that string will be matched, returning an empty string "". </p>
<p>When we are using a programming language, we can check if the regex returned an empty string and determine that the constraints are not satisfied.</p>
<p>We will create a regex which imposes the following criteria:</p>
<ol>
<li>Minimum 8 characters and maximum 16 characters.</li>
<li>At least one lower case letter.</li>
<li>At least one upper case letter.</li>
<li>At least one number.</li>
</ol>
<p>To achieve this, you can use positive lookaheads. This is the regex:</p>
<p><code>^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,16}$</code></p>
<p>The table below explains which part of the regex imposes which constraint:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Pattern</td><td>Imposed Constraint</td></tr>
</thead>
<tbody>
<tr>
<td><code>.{8,16}</code></td><td>min 8 and max 16 characters</td></tr>
<tr>
<td><code>(?=.*[a-z])</code></td><td>minimum one lower case letter</td></tr>
<tr>
<td><code>(?=.*[A-Z])</code></td><td>minimum one upper case letter</td></tr>
<tr>
<td><code>(?=.*\d)</code></td><td>minimum one digit</td></tr>
</tbody>
</table>
</div><p><img src="https://www.freecodecamp.org/news/content/images/2023/07/pass_constraints.png" alt="pass_constraints" width="600" height="400" loading="lazy"></p>
<p>What modification you would need for imposing at least 5 upper case letters?</p>
<p>You may think <code>(?=.*[A-Z]{5,})</code> will do the job. But this expression requires all the 5 letters to be together. A string like <code>rand-ABCDE-rand</code> will be matched but <code>0AxBCDxE0</code> will not be matched even though it has 5 upper case letters (as they are not adjacent).</p>
<p>Yet again, we have capture groups coming to the rescue. We want to match 5 uppercase letters anywhere in the string. We already know that we can match 1 uppercase letter with <code>.*[A-Z]</code>. Now we will put them inside a capture group and attach a quantifier of minimum 5. The expression will be <code>(.*[A-Z]){5,}</code>.</p>
<p>Here is the final answer:</p>
<p>In place of <code>(?=.*[A-Z])</code> you will need <code>(?=(.*[A-Z]){5,})</code>. The expression becomes <code>^(?=.*[a-z])(?=(.*[A-Z]){5,})(?=.*\d).{8,16}$</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/pass_5_upper.png" alt="pass_5_upper" width="600" height="400" loading="lazy"></p>
<p>You could also require that the password not contain certain words to enforce stronger passwords. </p>
<p>For example, we want to reject the password if contains <code>pass</code> or <code>1234</code>. Negative lookaheads is the tool for this job. The regex would be <code>^(?!.*(pass|1234)).*$</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/restrict_words-1.png" alt="restrict_words-1" width="600" height="400" loading="lazy"></p>
<p>In this regex, we put <code>pass</code> and <code>1234</code> inside a capture group and used the logical OR operator. This capture group is nested inside another capture group which is prefixed with <code>?!.*</code>. This makes it a negative lookahead that matches if there are at least 8 characters by <code>.{8,}</code> with the condition that, <code>pass</code> or <code>1234</code> can't be present anywhere in the string.</p>
<p><a></a></p>
<h2 id="heading-final-words">Final Words</h2>
<p>I hope you got a good amount of practice while going through this article. It's ok if you forget some syntax. What's important is understanding the core concepts and having a good idea of what's possible with regex. Then, if you forget a pattern, you can just google it or reference a cheatsheet. </p>
<p>The more you practice, the more you will get by without outside help. Eventually you will be able write super complex and effective regex completely offline. </p>
<p>There are already some good regex cheatsheets out there, so I wanted to create something more in-depth here that you can reference for the core concepts and common use cases. </p>
<p>If you're looking for a cheatsheet, the one from <a href="https://quickref.me/regex.html" target="_blank">QuickRef</a> is helpful. It's a good place to recall the syntax and they also provide some basic overview of regex related functions in various programming languages.</p>
<p>Most regex techniques are the same in all programming languages and tools – but certain tools might offer additional features. So do some research on the tool you are using to pick the best one for you.</p>
<p>My final suggestion would be not to force using regex just because you can. A lot of the times a regular <code>string.find()</code> is enough to get the job done. But if you live in the terminal, you really can do a lot just with regex for sure.</p>
<p>If you like this type of article, you may keep an eye on my <a href="https://blog.renzhamin.com" target="_blank">blog</a> or twitter.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Regular Expressions Book – RegEx for JavaScript Developers [Full Book] ]]>
                </title>
                <description>
                    <![CDATA[ If you want to master regular expressions and understand how they work in JavaScript, this book's for you. Regular expressions can be intimidating when you first encounter them. When I started learning to code, I gave up on regular expressions twice.... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/regular-expressions-for-javascript-developers/</link>
                <guid isPermaLink="false">66adf1f6f452caf50fb1fe18</guid>
                
                    <category>
                        <![CDATA[ book ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Regex ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Regular Expressions ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Wed, 26 Jul 2023 15:27:12 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/07/Regex-for-JavaScript-Developers-Cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you want to master regular expressions and understand how they work in JavaScript, this book's for you.</p>
<p>Regular expressions can be intimidating when you first encounter them. When I started learning to code, I gave up on regular expressions twice.</p>
<p>While that was partly because I was intimidated by regular expressions at first, the tutorials and courses I used never taught them in a way I could understand. </p>
<p>In fact, before some tutorials start teaching regex, they complain about regex and how tough they can be. And there's no better way to discourage a learner than that.</p>
<p>In this book, you won't just see how to use regex in a regex testing tool like <strong>regexpal</strong> or <strong>regex101</strong>. You'll also see how they works in JavaScript. This is what many courses and tutorials tailored for regex in JavaScript lack. As you see how they work using a regex tester, you'll also see how they work in JavaScript.</p>
<p>You can also apply what you learn in this book to other programming languages like Python, PHP, and so on. All you need to do is to know about how the regex engine of that language works. You'll also need to understand the methods and functions the language uses for working with regular expressions.</p>
<p>To get the most out of this book, make sure you read it in order because each chapter builds upon the previous ones. I have also arranged the chapters according to how difficult they are. So, you will find simpler concepts first and more advanced concepts later.</p>
<p>Happy reading!</p>
<h2 id="heading-table-of-contents">Table Of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-chapter-1-introduction-to-regular-expressions">Chapter 1: Introduction to Regular Expressions</a><ul>
<li><a class="post-section-overview" href="#heading-what-are-regular-expressions">What are Regular Expressions?</a></li>
<li><a class="post-section-overview" href="#heading-a-brief-history-of-regular-expressions">A Brief History of Regular Expressions</a></li>
<li><a class="post-section-overview" href="#heading-what-are-the-uses-of-regular-expressions">What are the Uses of Regular Expressions?</a></li>
<li><a class="post-section-overview" href="#heading-flavors-of-regular-expressions">Flavors of Regular Expressions</a></li>
<li><a class="post-section-overview" href="#heading-tools-for-working-with-regular-expressions">Tools for Working with Regular Expressions</a></li>
<li><a class="post-section-overview" href="#heading-basic-concepts-of-regular-expressions">Basic Concepts of Regular Expressions</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-2-how-to-match-literal-characters-and-character-sets-in-regular-expressions">Chapter 2: How to Match Literal Characters and Character Sets in Regular Expressions</a><ul>
<li><a class="post-section-overview" href="#heading-what-are-literal-characters-in-regular-expressions">What are Literal Characters in Regular Expressions?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-match-literal-characters-in-regex-testers">How to Match Literal Characters in RegEx Testers</a></li>
<li><a class="post-section-overview" href="#heading-character-set-matching">Character Set Matching</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-3-regular-expressions-flags">Chapter 3: Regular Expressions Flags</a><ul>
<li><a class="post-section-overview" href="#heading-the-global-flag">The <code>global</code> Flag</a></li>
<li><a class="post-section-overview" href="#heading-the-case-insensitive-flag">The <code>case-insensitive</code> Flag</a></li>
<li><a class="post-section-overview" href="#heading-the-multi-line-and-single-line-flags">The <code>multi-line</code> and <code>single-line</code> Flags</a></li>
<li><a class="post-section-overview" href="#heading-the-unicode-flag">The <code>unicode</code> Flags</a></li>
<li><a class="post-section-overview" href="#heading-the-sticky-flag">The <code>sticky</code> Flags</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-4-how-to-use-regular-expressions-in-javascript">Chapter 4: How to Use Regular Expressions in JavaScript </a><ul>
<li><a class="post-section-overview" href="#heading-how-to-create-regular-expressions-in-javascript">How to Create Regular Expressions in JavaScript</a></li>
<li><a class="post-section-overview" href="#heading-methods-of-the-regexp-constructor">Methods of the <code>RegExp()</code> Constructor</a></li>
<li><a class="post-section-overview" href="#heading-properties-of-the-regexp-constructor">Properties of the <code>RegExp()</code> Constructor</a></li>
<li><a class="post-section-overview" href="#heading-string-methods-for-working-with-regular-expressions">String Methods for Working with Regular Expressions</a></li>
<li><a target="_blank" href="howtomatchliteralcharactersinjavascriptregularexpressions">How to Match Literal Characters in JavaScript Regular Expressions</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-character-sets-in-javascript-regular-expressions">How to Use Character Sets in JavaScript Regular Expressions</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-5-metacharacters-quantifiers-repeated-matches-and-optional-matches">Chapter 5: Metacharacters, Quantifiers, Repeated Matches, and Optional Matches</a><ul>
<li><a class="post-section-overview" href="#heading-what-are-metacharacters">What are Metacharacters?</a></li>
<li><a class="post-section-overview" href="#heading-the-word-and-non-word-metacharacters">The Word and Non-word Metacharacters</a></li>
<li><a class="post-section-overview" href="#heading-the-anchor-metacharacters">The Anchor Metacharacters</a></li>
<li><a class="post-section-overview" href="#heading-the-digit-and-non-digit-metacharacters">The Digit and Non-digit Metacharacters</a></li>
<li><a class="post-section-overview" href="#heading-the-square-brackets-metacharacter">The Square Brackets Metacharacter</a></li>
<li><a class="post-section-overview" href="#heading-the-word-boundary-and-non-word-boundary-metacharacters">The Word Boundary and Non-word Boundary Metacharacters</a></li>
<li><a class="post-section-overview" href="#heading-the-parenthesis-metacharacter">The Parenthesis Metacharacter</a></li>
<li><a class="post-section-overview" href="#heading-the-space-and-non-space-metacharacters">The Space and Non-space Metacharacters</a></li>
<li><a class="post-section-overview" href="#heading-the-pipe-metacharacter">The Pipe Metacharacter</a></li>
<li><a class="post-section-overview" href="#heading-how-to-match-repeated-characters-with-quantifiers">How to Match Repeated Characters With Qunatifiers</a></li>
<li><a class="post-section-overview" href="#heading-how-to-specify-match-quantity-with-the-curly-braces-metacharacter">How to Specify Match Quantity with the Curly Braces Metacharacter</a></li>
<li><a class="post-section-overview" href="#heading-the-wildcard-metacharacter">The Wildcard Metacharacter</a></li>
<li><a class="post-section-overview" href="#heading-greediness-and-laziness-in-regular-expressions">Greediness and Laziness in Regular Expressions</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-6-grouping-and-capturing-in-regex">Chapter 6: Grouping and Capturing in Regex</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-reference-captured-groups-with-backreferences">How to Reference Captured Groups with Backreferences</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-d-flag-and-hasindices-property-with-groups">How to Use the <code>d</code> Flag and <code>hasIndices</code> Property With Groups</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-7-lookaround-groups-lookaheads-and-lookbehinds">Chapter 7: Lookaround Groups: Lookaheads and Lookbehinds</a> <ul>
<li><a class="post-section-overview" href="#heading-what-are-lookaround-groups">What are Lookaround Groups?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-lookahead-group">What is a Lookahead Group?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-lookbehind-group">What is a Lookbehind Group?</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-8-regex-best-practices-and-troubleshooting">Chapter 8: Regex Best Practices and Troubleshooting</a><ul>
<li><a class="post-section-overview" href="#heading-best-practices-to-consider-while-writing-regular-expressions">Best Practices to Consider While Writing Regular Expressions</a></li>
<li><a class="post-section-overview" href="#heading-how-to-write-accurate-regular-expressions">How to Write Accurate Regular Expressions</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-9-applications-of-regular-expressions">Chapter 9: Applications of Regular Expressions</a><ul>
<li><a class="post-section-overview" href="#heading-a-better-way-to-match-dates">A Better Way to Match Dates</a> </li>
<li><a class="post-section-overview" href="#heading-how-to-match-us-zip-codes">How to Match US Zip Codes</a></li>
<li><a class="post-section-overview" href="#heading-how-to-match-email-addresses">How to Match Email Addresses</a></li>
<li><a class="post-section-overview" href="#heading-how-to-match-passwords">How to Match Passwords</a></li>
<li><a class="post-section-overview" href="#heading-form-validation-with-regex">Form Validation with Regex</a></li>
<li><a class="post-section-overview" href="#heading-article-table-of-contents-generator">Article Table of Contents Generator</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-glossary-and-references">Glossary and References</a><ul>
<li><a class="post-section-overview" href="#heading-glossary-of-terms">Glossary of Terms</a> </li>
<li><a class="post-section-overview" href="#heading-quick-reference-of-metacharacters-and-quantifiers">Quick Reference of Metacharacters and Quantifiers</a> </li>
</ul>
</li>
</ul>
<h2 id="heading-chapter-1-introduction-to-regular-expressions">Chapter 1: Introduction to Regular Expressions</h2>
<h3 id="heading-what-are-regular-expressions">What are Regular Expressions?</h3>
<p>You might see this written as regular expressions, regex, or RegExp – but all refer to the same thing. </p>
<p>Regex are a sequence of characters for matching a part of a string or the whole string. Matching strings with regular expressions might require more than just "characters". Many times, you will need to use a special set of characters called "metacharacters" and "quantifiers". </p>
<p>Because regular expressions are a powerful tool, you can use then to do much more than just "matching strings" when you combine regex with programming languages. </p>
<p>Almost all the main programming languages of the modern era have built-in support for regular expressions. Some programming languages might even have specific libraries that help you work more conveniently with regex.</p>
<p>Apart from using regular expressions in programming languages, other tools that let you use regular expressions are:</p>
<ul>
<li><p><strong>Text Editors and IDEs</strong>: for search and search and replace in VS Code, Visual Studio, Notepad++, Sublime Text, and others.</p>
</li>
<li><p><strong>Browser Developer Tools</strong>: mostly in-browser search (with extensions or add-ons) and search within the developer tools.</p>
</li>
<li><p><strong>Database Tools</strong>: for data mining.</p>
</li>
<li><p><strong>RegEx Testers</strong>: you can paste in text and write the regular expressions to match them – which is a very good way to learn regular expressions. This book explores that option quite a bit.</p>
</li>
</ul>
<h3 id="heading-a-brief-history-of-regular-expressions">A Brief History of Regular Expressions</h3>
<p>Regular expressions have a rich and fascinating history that has already spanned more than seven decades. This history continues to evolve alongside the development of computer science and programming languages.</p>
<p>The concept of regular expressions traces back to the 1950s. American mathematician Stephen Cole Kleene introduced them as a notation for defining patterns in formal languages. Kleene's work also formed the foundation for theoretical computer science.</p>
<p>In the early 1960s, the first implementations of regular expressions emerged. Ken Thompson, a computer scientist at Bell Labs, developed a text editor named <strong>QED</strong> that utilized regular expressions for pattern matching. QED's capabilities provided a way to search and manipulate texts more efficiently.</p>
<p>The concept gained further popularity when Thompson and Dennis Ritchie created the Unix operating system in the early 1970s. </p>
<p>They incorporated regular expressions into various Unix utilities, most notably the <strong>ed text editor</strong> and later the <strong>sed stream editor</strong>. These tools allowed users to perform complex text manipulation tasks, significantly enhancing the efficiency and power of text processing.</p>
<p>In 1973, Thompson collaborated with Alfred Aho and Peter Weinberger to develop a new tool called <strong>grep</strong> (global regular expression print) as part of the Unix toolkit. </p>
<p>Grep allowed users to search files for specific patterns using regular expressions. The simplicity and effectiveness of grep made it a widely adopted tool. It also established regular expressions as a standard feature in Unix-based systems.</p>
<p>As computer systems and programming languages evolved, regular expressions became integrated into various software development environments. In the late 1970s, the AWK programming language was created. AWK inspired Larry Wall to create Perl and make it available to the public in 1987.</p>
<p>Wall recognized the value of regular expressions for text manipulation and integrated regex into Perl. </p>
<p>Perl's integration of regular expressions into its syntax made it a popular language for text matching and data extraction tasks. This integration formed the foundation of  <strong>PCRE</strong> (Perl-compatible regular expressions), a flavor and library of regular expressions you can use in some programming languages such as Perl, Python, PHP, Java, and others.</p>
<p>Regular expressions continued to evolve and find applications beyond Unix and Perl. In the 1980s, the International Organization for Standardization (ISO) developed the POSIX standard, which included a specification for regular expressions. This standardization ensured compatibility and consistency across different implementations and systems.</p>
<p>With the rise of the internet and the World Wide Web in the 1990s, regular expressions found widespread use in web development and data processing. They became an essential component of many scripting languages, providing developers with powerful tools for text processing, form validation, and data extraction from web pages. </p>
<p>For example, JavaScript had always had a version of PCRE built in for working with regular expressions. But by 1999, with the release of ECMAScript, the <code>RegExp()</code> constructor was introduced. This gave JavaScript developers the ability to start using regular expressions directly in their code, in the JavaScript way.</p>
<p>In the early 2000s, tools and libraries specifically focused on regular expressions emerged, making it easier for developers to work with them. Libraries like PCRE (Perl Compatible Regular Expressions) provided enhanced features and better performance, further expanding the usage and capabilities of regular expressions.</p>
<p>Today, regular expressions are an integral part of programming languages and text-processing tools like your code editor. They are supported by almost all major programming languages, including Java, C#, Ruby, and PHP. </p>
<p>Integrated development environments (IDEs) and code editors like Visual Studio, VS Code, and Notepad++ also now include regex-based search and search and replace functionalities, simplifying the process of finding and manipulating texts in code. </p>
<p>The history of regular expressions demonstrates their evolution from theoretical concepts to practical tools that have revolutionized text processing and pattern matching. </p>
<p>From the early developments at Bell Labs and Unix to their integration into popular programming languages, regular expressions have become an essential tool in the hands of developers and system administrators. Regex empowers them to handle complex text-based tasks efficiently. </p>
<p>With the ongoing advancements in computing and the continuous demand for efficient text processing, regular expressions will likely remain a fundamental part of the technology landscape for years to come.</p>
<h3 id="heading-what-are-the-uses-of-regular-expressions">What are the Uses of Regular Expressions?</h3>
<p>Regular expressions are quite versatile and flexible. This makes it possible to apply them to various tasks in various domains such as computer programming, data processing, text editing, and web development.</p>
<p>Those applications and uses include but are not limited to the following:</p>
<p><strong>String Matching</strong>: This is one of the most common ways developers use regular expressions. This is also a good way to learn regular expressions. </p>
<p>You can paste some texts into a regex engine and write the regex to match a part of the text or the whole text. You can also search for strings that contain specific character sequences, start or end with certain characters, or match complex patterns. </p>
<p>This makes regular expressions valuable for tasks like searching for keywords, validating input against specific patterns, or filtering data based on string patterns</p>
<p><strong>Password Strength Validation</strong>: You can use regular expressions for validating the strength of passwords in websites and applications. </p>
<p>By defining a set of rules using regular expressions, developers can enforce specific password requirements, such as a minimum number of characters, a combination of uppercase and lowercase letters, numbers, and special characters. </p>
<p><strong>Form Validation</strong>: Validating inputs of a form or standalone inputs is another popular way developers use regular expressions. </p>
<p>Regular expressions provide a concise and efficient way to ensure that input data follows specific patterns or formats. Whether it's validating usernames, email addresses, phone numbers, credit card numbers, postal codes, or other inputs, regular expressions can help you enforce validation rules and maintain data integrity.</p>
<p><strong>Text Search and Manipulation</strong>: Regular expressions excel at searching for specific patterns within text and performing manipulations based on those matches. They are a powerful tool for tasks such as data mining, log analysis, and text processing. </p>
<p>Whether you need to find occurrences of particular words or phrases, extract structured data from text, analyze content, or perform string matching, regular expressions offer efficient pattern-matching capabilities</p>
<p><strong>Working with URLs and URIs</strong>: Since URLs and URIs are an integral part of web development, regular expressions can help in validating, parsing, and manipulating them. This enables developers to ensure the correctness and structure of web addresses, validate whether a string is a valid URL, and help extract specific components such as the domain, path, query parameters, or fragments. </p>
<p>This functionality is particularly useful in tasks like URL routing, rewriting, or extracting data from query parameters.</p>
<p><strong>Search and Replace in IDEs and Text Editors</strong>: Regular expressions offer sophisticated search capabilities. This enables developers to locate specific patterns (such as words with specific prefixes or sequences of characters) and then replace the matches with a specified text. This is built into modern text editors like VS Code and Notepad++.</p>
<p><strong>Data Extraction and Scraping</strong>: Regular expressions play a significant role in data extraction and web scraping. They allow developers to extract specific information from unstructured or semi-structured text by defining patterns to match desired data. </p>
<p>They are also valuable when extracting data from sources like HTML or XML documents, as they enable efficient retrieval of information based on defined patterns.</p>
<p><strong>Syntax Highlighting</strong>: Regular expressions are commonly used in IDEs and text editors to provide syntax highlighting. This ends up helping users to visually distinguish different parts of a code or document by assigning colors or formatting to keywords, strings, comments, and other language-specific constructs. </p>
<p>Regular expressions are used to identify and match these language-specific patterns, making code more readable and enhancing the overall editing experience.</p>
<h3 id="heading-flavors-of-regular-expressions">Flavors of Regular Expressions</h3>
<p>The term "flavors of regular expressions" refers to the specific implementation and syntax variations of regular expressions in different programming languages, libraries, or tools. </p>
<p>While the core concept of regular expressions remains the same, the details of how regular expressions are written and interpreted can vary between different environments.</p>
<p>Each flavor of regular expressions may have its own set of metacharacters, syntax rules, and additional features beyond the basic functionality. </p>
<p>These differences can include variations in the syntax for character classes, metacharacters, capturing groups, and assertions, as well as additional capabilities like named capturing groups, look-ahead, and look-behinds.</p>
<p>There are many flavors of regular expressions available today. Some of them are:</p>
<ul>
<li><p><strong>Basic Regular Expressions (BRE)</strong>: this flavor is commonly found in Unix tools such as <strong>sed</strong> and <strong>grep</strong>. It uses a limited set of metacharacters and features. The wildcard (<code>.</code>) and zero or more (<code>*</code>) metacharacters are available in it.</p>
</li>
<li><p><strong>Extended Regular Expressions (ERE)</strong>: ERE is an extension of BRE. It provides additional metacharacters and features. In addition to the metacharacters available in BRE, ERE introduces features like grouping with parentheses ( <code>( )</code>), alternation with the pipe symbol (<code>|</code>), and the use of curly braces (<code>{}</code>) to specify repetition ranges.</p>
</li>
<li><p><strong>Perl-Compatible Regular Expressions (PCRE)</strong>: PCRE is a popular flavor supported by various programming languages such as Perl, Python, PHP, and JavaScript. PCRE extends the basic regular expression syntax with powerful features like lookahead and look-behind assertions, backreferences, non-capturing groups, and the use of <code>\b</code> for word boundaries.</p>
</li>
<li><p><strong>JavaScript Regular Expressions</strong>: JavaScript has its regular expression flavor which is similar to PCRE but with a few differences. It supports basic features like character classes with square brackets (<code>[ ]</code>), metacharacters (<code>*</code>, <code>+</code>, <code>?</code>, and others), and capturing groups  (<code>( )</code>). JavaScript also provides additional features like the global flag <code>/g</code> to perform multiple matches, and the ignore case flag <code>/i</code> for case-insensitive matching</p>
</li>
<li><p><strong>Python Regular Expressions</strong>: Python's <code>re</code> module implements a flavor that is similar to PCRE but with a few variations. It supports features such as character classes <code>[ ]</code>, metacharacters (<code>*</code>, <code>+</code>, and <code>?</code>), and capturing groups (<code>( )</code>). The <code>re</code> module also has a unique raw string syntax (<code>r' '</code>) to simplify working with backslashes.</p>
</li>
</ul>
<p>It's important to be aware of the flavor of regular expressions you are using when working with regular expressions in different programming languages or tools. This ensures that you use the correct syntax and take advantage of any unique features or capabilities provided by that particular flavor.</p>
<p><strong>N.B.</strong>: Don’t bother so much about the metacharacters (and quantifiers) mentioned in this part. You will see them in action in chapter 5 of this book.</p>
<h3 id="heading-tools-for-working-with-regular-expressions">Tools for Working with Regular Expressions</h3>
<p>Regular expression tools are the programming languages, libraries and frameworks, command line utilities, online regex testers, text editors and IDEs, and applications designed to help you create, test, and apply regular expressions in your day-to-day work life.</p>
<p>There are many tools available for working with regular expressions. Let me take you through them under regex testers, programming languages, libraries, text editors and IDEs, and command line tools.</p>
<h4 id="heading-regex-testers">RegEx Testers</h4>
<p>RegEx testers are the online testing environments specifically built for creating and testing regular expressions against some test strings. Examples include regex101.com, regexr.com, and regexpal.com.</p>
<p>The UIs of these regex testers usually have an input for the regular expressions you want to write, and another for the text you want to test the regex against. </p>
<p>This is how the UI of regexpal.com looks:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/regexpal-ui.png" alt="regexpal-ui" width="600" height="400" loading="lazy"></p>
<p>More advanced ones like regex101.com let you select the flavor of regular expressions you want to work with, an explanation of the regex, and match information. </p>
<p>Here’s what the UI of regex101.com looks like:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/regex101-ui-1.png" alt="regex101-ui-1" width="600" height="400" loading="lazy"></p>
<p>One of the good things about these online regex testers is that they are helpful for learning regular expressions. A lot of them provide real-time matching and cheatsheets you can quickly look at. Many devs who use regex have used them. </p>
<p>Apart from learning, you can also use them by creating your regex with them and pasting them into wherever you want to use the regex. This is how I create my regex.</p>
<h4 id="heading-programming-languages">Programming Languages</h4>
<p>Almost all modern programming languages have built-in support for regular expressions. And so they all have methods for creating and testing regular expressions. </p>
<p>For example, JavaScript has the <code>RegExp()</code> constructor for working with regular expressions, Python has the <code>re</code> module, Java has the <code>java.util.regex</code> package, and Perl has regex built into it directly.</p>
<h4 id="heading-libraries-and-frameworks">Libraries and Frameworks</h4>
<p>Many programming languages have standalone libraries and frameworks that make it easier to create regular expressions. </p>
<p>There is <code>XRegExp</code> for JavaScript, PCRE (Perl Compatible Regular Expressions) for Perl, Go-Restructure for Golang, and Verbal Expressions, a cross-platform regex library.</p>
<h4 id="heading-text-editors-and-ides">Text Editors and IDEs</h4>
<p>Many text editors and IDEs such as VS Code, Visual Studio, Notpad++, Atom, Sublime Text, IntelliJ IDEA, and others have built-in support for regular expressions. </p>
<p>The commonest thing developers use this for is search, and search and replace. Also, the syntax highlighting in those text editors and IDEs is often implemented with regular expressions.</p>
<h4 id="heading-command-line-tools">Command Line Tools</h4>
<p>Unix command line tools like grep and sed allow you to perform regex operations on text files and streams. With this, you can search, filter, and manipulate multiple files. </p>
<p>Using these Unix tools, options for customizing search behaviors and customizing complex text transformations are also available to you.</p>
<h3 id="heading-basic-concepts-of-regular-expressions">Basic Concepts of Regular Expressions</h3>
<p>The basic concepts and syntax of regular expressions are the building blocks involved in creating, testing, and applying patterns for searching, matching, and manipulating strings. </p>
<p>This includes concepts like <strong>literal characters</strong>, <strong>metacharacters</strong>, <strong>quantifiers</strong>, <strong>character classes</strong>, <strong>anchors and boundaries</strong>, and <strong>escape characters</strong>. The more advanced ones are <strong>groupings</strong>, <strong>backreferences</strong>, <strong>look-ahead assertions</strong>, and <strong>look-behind assertions</strong>.</p>
<p>Regular expressions users utilize many of these concepts to construct efficient regular expressions for working with text. On many occasions, the basic ones are enough. But if you want to create more advanced regular expressions, then the more advanced ones will also be useful for you.</p>
<p>This book won’t leave any of the concepts behind. I will show you how you can utilize them in regex testers and how you can use them in JavaScript since that’s what this book is meant for.</p>
<h2 id="heading-chapter-2-how-to-match-literal-characters-and-character-sets-in-regular-expressions">Chapter 2: How to Match Literal Characters and Character Sets in Regular Expressions</h2>
<h3 id="heading-what-are-literal-characters-in-regular-expressions">What are Literal Characters in Regular Expressions?</h3>
<p>Literal characters are characters you can match as they appear in a test string. They could be letters, numbers, spaces, or even symbols. In other words, they are non-special characters that represent themselves.</p>
<p>This means if you want to match literal characters, you should construct your regex pattern in the same way as the test string appears. </p>
<p>For example, if you want to match the word <code>hello</code>, your regex pattern can be <code>hello</code>. And if you want to match the <code>h</code> in the word <code>hatch</code>, all you need as the pattern is <code>h</code>. </p>
<p>This <code>h</code> would match the first occurrence of the letter <code>h</code> in the test string <code>hatch</code>. If you want it to match the other letter <code>h</code> as well, you need the "g" flag, or global flag. You will learn about the flags and modifiers in the next chapter of this book.</p>
<p>That is not the case for some symbols, though. That’s because some symbols are special characters of regular expressions (metacharacters and quantifiers). So, if you want to match those characters, you have to escape them with a backslash (<code>\</code>). This book will also teach you all you need to know about metacharacters because there's a whole chapter for them.</p>
<h3 id="heading-how-to-match-literal-characters-in-regex-testers">How to Match Literal Characters in RegEx Testers</h3>
<p>Provided you want to match the word <code>hello</code>, then <code>hello</code> should be your regex pattern:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/hello-match-1.png" alt="hello-match-1" width="600" height="400" loading="lazy"></p>
<p>If you want to match the text <code>freeCodeCamp</code>, you can construct your regex to be <code>freeCodeCamp</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/fcc-match-1.png" alt="fcc-match-1" width="600" height="400" loading="lazy"></p>
<p>So, what if you want to match <code>hello freeCodeCamp</code>? Then you just use <code>hello freeCodeCamp</code> as the pattern:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/hello-fcc-match.png" alt="hello-fcc-match" width="600" height="400" loading="lazy"></p>
<p>If you want to match the letter <code>e</code> in the text <code>freeCodeCamp</code>, <code>e</code> is the pattern to use:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/e-in-fcc.png" alt="e-in-fcc" width="600" height="400" loading="lazy"></p>
<p>And if you want to match <code>h</code> in the text <code>hatch</code>, <code>h</code> is the pattern you should use:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/h-in-hatch.png" alt="h-in-hatch" width="600" height="400" loading="lazy"></p>
<p>You can see that in the text <code>freeCodeCamp</code>, the other <code>e</code>s after the first occurrence were not returned as matches – same with the last <code>h</code> in the word <code>hatch</code>. You will learn how to match every occurrence of a letter in a text in the next chapter.</p>
<h3 id="heading-character-set-matching">Character Set Matching</h3>
<p>A character set, also called character class, is a set of characters that will successfully match a certain character in a test string. This set of characters is enclosed in square brackets. </p>
<p>For instance, the pattern <code>[abc]</code> will match any of <code>a</code>, <code>b</code>, and <code>c</code>, while <code>[xyz]</code> will match any of <code>x</code>, <code>y</code>, and <code>z</code>.</p>
<p>Here are some examples of character sets and what they do:</p>
<ul>
<li><code>[abc]</code>: matches either <code>a</code>, <code>b</code>, or <code>c</code></li>
<li><code>[aeiou]</code>: matches any vowel character</li>
<li><code>[a-z]</code>: matches any lowercase letter from <code>a</code> to <code>z</code></li>
<li><code>[A-Z]</code>: matches any uppercase letter from <code>A</code> to <code>Z</code></li>
<li><code>[0-9]</code>: matches any digit from 0 to 9</li>
</ul>
<p>Inside the square brackets, you don’t need to escape metacharacters because they lose their special meaning. The only symbol that has a meaning in the square brackets is a hyphen (<code>-</code>), which you can use to specify ranges, as I have done with some examples of character sets. </p>
<p>You will also learn about ranges in this book. On some occasions, a backslash <code>\</code> does not lose its special meaning in a character set.</p>
<p>As with literal character matching, only the first occurrence of the character set will return as a match, every other occurrence will be ignored. In the next chapter, you will learn how to match multiple occurrences of a character with the <code>g</code> flag.</p>
<p>Here’s how each of the above character sets works in a regex testing tool:</p>
<p><code>[abc]</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/-abc--match.png" alt="-abc--match" width="600" height="400" loading="lazy"></p>
<p><code>[aeiou]</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/vowels-match.png" alt="vowels-match" width="600" height="400" loading="lazy"></p>
<p><code>[a-z]</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/lcase-set-match.png" alt="lcase-set-match" width="600" height="400" loading="lazy"></p>
<p><code>[A-Z]</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/ucase-set-match.png" alt="ucase-set-match" width="600" height="400" loading="lazy"></p>
<p><code>[0-9]</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/number-set-match.png" alt="number-set-match" width="600" height="400" loading="lazy"></p>
<p>You can also define your unique character class based on what you want. Character sets are useful when you want to match some characters in a particular position in a text.</p>
<p>For instance, the pattern <code>br[ao]ke</code> will match both <code>brake</code> and <code>broke</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/brakebroke-match.png" alt="brakebroke-match" width="600" height="400" loading="lazy"></p>
<p>The pattern <code>gr[ae]y</code> will match both <code>gray</code> and <code>grey</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/graygrey-match.png" alt="graygrey-match" width="600" height="400" loading="lazy"></p>
<p><strong>N.B.</strong>: I turned on the <code>g</code> flag so you can see all the matches, and how powerful character sets are. We will take a look at the <code>g</code> and other flags in the next chapter.</p>
<p>Since there are always multiple ways of doing the same thing in programming, there are also certain character sets called "shorthand character sets" that you can use instead of character sets. </p>
<p>Since these shorthand character sets are a subset of metacharacters, you will learn about them under the chapter dedicated to metacharacters.</p>
<h2 id="heading-chapter-3-regular-expressions-flags">Chapter 3: Regular Expressions Flags</h2>
<p>Also called modifiers, flags are special characters you can place at the end or within a regular expressions pattern to alter its default behavior. </p>
<p>JavaScript developers tend to refer to these characters as "flags", but in Python they are used interchangeably. </p>
<p>In Python, you can place flags within a regex pattern, but in JavaScript, flags are always placed at the end of the regex pattern.</p>
<p>Here are the flags you can use in regular expressions:</p>
<ul>
<li><code>global</code> flag</li>
<li><code>case insensitive</code> flag</li>
<li><code>multi-line</code> flag</li>
<li><code>single-line</code> flag</li>
<li><code>unicode</code> flag</li>
<li><code>sticky</code> flag</li>
</ul>
<p>In many regex engines, you can turn on any flag you want to use. In regex101.com, you can turn on a flag by clicking on the slash symbol (<code>/</code>) right inside the pattern input: </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/turn-on-a-flag-101.png" alt="turn-on-a-flag-101" width="600" height="400" loading="lazy"></p>
<p>You can then select any flag you want to use:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/select-flag-101.png" alt="select-flag-101" width="600" height="400" loading="lazy"></p>
<p><strong>N.B.</strong>: If the flavor of regex you selected in regex101.com is not ECMAScript, the set of flags presented to you might be different.</p>
<p>If you are using regexpal.com, click on "flags" above the regex pattern input:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/turn-on-flag-pal.png" alt="turn-on-flag-pal" width="600" height="400" loading="lazy"></p>
<p>Select any flag you want by clicking on it:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/select-flag-pal.png" alt="select-flag-pal" width="600" height="400" loading="lazy"></p>
<p>Now, let's take a detailed look at each of the regex flags and how they work in a regex engine.</p>
<h3 id="heading-the-global-flag">The <code>global</code> Flag</h3>
<p>The <code>global</code> flag is denoted by the letter <code>g</code>. With it, you get to perform a global match with your pattern. </p>
<p>Remember in the previous chapter of this book, some patterns I defined stopped when they found the first match, even if there were more. That’s because by default, regular expressions only find the first match in a text. But with the <code>g</code> flag, all occurrences of the match are returned.</p>
<p>Another good thing about using the <code>g</code> flag is that you can iterate over the matches you get with the pattern in JavaScript. The iteration continues until there’s nothing to match. You will learn about multiple ways you can iterate over matches soon.</p>
<p>To let you see how the <code>g</code> flag works, I’ll use the <code>hatch</code> and <code>freeCodeCamp</code> examples from the previous chapter.</p>
<p>If you want to match the letters <code>h</code> in the word <code>hatch</code> with the pattern <code>h</code>, both the first and the last <code>h</code>s will be returned as matches as long as you have the <code>g</code> flag on:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/h-in-hatch-g-match.png" alt="h-in-hatch-g-match" width="600" height="400" loading="lazy"></p>
<p>And if you want to match <code>e</code> in <code>freeCodeCamp</code> with the pattern <code>e</code> and you turn on the <code>g</code> flag, the second and third <code>e</code>s are returned as a match too:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/e-in-fcc-g-match.png" alt="e-in-fcc-g-match" width="600" height="400" loading="lazy"></p>
<h3 id="heading-the-case-insensitive-flag">The <code>case-insensitive</code> Flag</h3>
<p>The <code>case insensitive</code> flag is denoted by <code>i</code>. As the name implies, it lets you perform case-insensitive matching.</p>
<p>By default, regular expressions perform case-sensitive matching. But with the <code>i</code> flag you can perform case-insensitive matching, so you won’t bother about casing in your patterns.</p>
<p>With this, uppercase or lowercase will be ignored. That means <code>Hello</code> and <code>hello</code> will be treated as the same thing:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/hello-insensitive.png" alt="hello-insensitive" width="600" height="400" loading="lazy"></p>
<p><code>freeCodeCamp</code> and <code>freecodecamp</code> are treated the same, too:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/fcc-insensitive.png" alt="fcc-insensitive" width="600" height="400" loading="lazy"></p>
<p><code>RegEx</code> and <code>regex</code> are also the same thing:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/regex-insensitive.png" alt="regex-insensitive" width="600" height="400" loading="lazy"></p>
<p>Another thing is that if you’re using a character class, for example <code>[a-z]</code>, it would match uppercase letters too if you turn on the <code>case-insensitive</code> flag.</p>
<p>So, the pattern <code>[a-z]</code> also matches uppercase letters with the <code>case-insensitive</code> flag turned on:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/carset-insensitive.png" alt="carset-insensitive" width="600" height="400" loading="lazy"></p>
<h3 id="heading-the-multi-line-and-single-line-flags">The <code>multi-line</code> and <code>single-line</code> Flags</h3>
<p>Denoted by <code>m</code>, the <code>multi-line</code> flag tells the regular expressions engine that the test string is more than one line. Since the <code>multi-line</code> flag influences the behavior of the start and end anchor metacharacters (<code>^</code> and <code>$</code>), you’ll learn more about it under the anchors and word boundaries chapter.</p>
<p>The <code>single-line</code> flag is denoted by <code>s</code>. Just like the <code>multi-line</code> flag, the <code>single-line</code> flag also works with a metacharacter called the wildcard (<code>.</code>).  You will see the <code>single-line</code> flag in action under the chapter for metacharacters.</p>
<h3 id="heading-the-unicode-flag">The <code>Unicode</code> Flag</h3>
<p>The Unicode flag enables full Unicode matching in the regular expressions engine that supports it. It is denoted by <code>u</code>.</p>
<p>By default, JavaScript and many other programming languages treat strings as a sequence of 16-bit code units. With the <code>u</code> flag, regex patterns can match against Unicode code points instead of code units. This allows handling characters like emojis, certain symbols, and characters from non-Latin scripts. So, when you set the flag, it modifies the behavior of certain escape sequences and metacharacters to work with regular expressions.</p>
<p>For example, the escape sequence <code>\u{1F602}</code> will match the literal character <code>u{1F602}</code> if you don’t turn on the <code>u</code> flag:
<img src="https://www.freecodecamp.org/news/content/images/2023/07/u-flag-literal-match.png" alt="u-flag-literal-match" width="600" height="400" loading="lazy"></p>
<p>But if you turn on the <code>u</code> flag, the same pattern matches the face with tears emoji:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/u-flag-emoji-match.png" alt="u-flag-emoji-match" width="600" height="400" loading="lazy"></p>
<p>That is one way to match emojis and other Unicode characters. Take the Unicode of the emoji and put the hexadecimal in curly braces, then precede the two with <code>\u</code>.</p>
<p>For instance, the Unicode of growing heart is <code>U+1F497</code>, the pattern to match it would be <code>\u{1F497}</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/growing-heart-match.png" alt="growing-heart-match" width="600" height="400" loading="lazy"></p>
<p>You will see more examples of how the flag works in the chapter on how to use regular expressions in JavaScript.</p>
<h3 id="heading-the-sticky-flag">The <code>sticky</code> Flag</h3>
<p>The sticky flag is denoted by <code>y</code>. It’s a feature of JavaScript regular expressions implemented in ECMAScript 6. The <code>y</code> flag limits matching to the current position in the string, which you can specify with the <code>lastIndex</code> property of the <code>RegExp()</code> constructor.</p>
<p>When you use the <code>y</code> flag, it uses the <code>lastIndex</code> property to determine where the next search will start. The pattern matches only if it occurs exactly at the lastIndex position or at the beginning of the string.</p>
<p>Unlike the global (<code>g</code>) flag, the <code>y</code> flag does not find all matches but stops after the first successful match.</p>
<p>In a regex engine like regex101.com, the <code>y</code> flag usually anchors to the start of the test string and stops there:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/anchor-flag-match.png" alt="anchor-flag-match" width="600" height="400" loading="lazy"></p>
<p>Since the <code>y</code> flag typically works with the <code>lastIndex</code> property of JavaScript regular expressions, we will look at more examples in the chapter on how to use regular expressions in JavaScript – specifically when we look at the <code>sticky</code> of the regular expressions constructor.</p>
<p>You can also combine multiple flags to write more complex syntax. For example, you can use the <code>g</code> flag with the <code>i</code> flag for global and case-insensitive matching:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/g-and-i-flag.png" alt="g-and-i-flag" width="600" height="400" loading="lazy"></p>
<h2 id="heading-chapter-4-how-to-use-regular-expressions-in-javascript">Chapter 4: How to Use Regular Expressions in JavaScript</h2>
<h3 id="heading-how-to-create-regular-expressions-in-javascript">How to Create Regular Expressions in JavaScript</h3>
<p>There are two ways you can create regular expressions in JavaScript. The first is with <strong>regex literal syntax</strong> and the second is with the <code>RegExp()</code> constructor.</p>
<p>To create a regular expression with the regex literal syntax, you have to enclose the pattern inside two forward slashes (<code>/</code>) like this:</p>
<pre><code class="lang-js">/regex pattern/
</code></pre>
<p>If you want to use one or more flags, it has to be after the second slash:</p>
<pre><code class="lang-js">/regex pattern/flag
</code></pre>
<p>Depending on your use case, you might have to assign the regex to a variable:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> regex = <span class="hljs-regexp">/regex pattern/</span>flag
</code></pre>
<p>The flag could be any of the flags available in the JavaScript regular expressions engine.</p>
<p>If you want to create regular expressions with the <code>RegExp()</code> constructor, you have to use the <code>new</code> keyword, then put the pattern and the flag inside the <code>RegExp()</code> brackets. </p>
<p>This is what the syntax looks like:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> regex = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(<span class="hljs-string">"regex pattern"</span>, <span class="hljs-string">"flag"</span>);
</code></pre>
<p>Since <code>RegExp()</code> is a constructor, there are some methods and properties available in it with which you can work with regular expressions. Whether you create your pattern with the literal syntax <code>//</code> or the <code>RegExp()</code> constructor, the methods and properties are available for it.</p>
<h3 id="heading-methods-of-the-regexp-constructor">Methods of the <code>RegExp()</code> Constructor</h3>
<p>The methods of the <code>RegExp()</code> constructor are defined on the <code>RegExp.prototype</code>. You can quickly check the methods (and properties) by typing <code>RegExp().__proto__</code> and hitting <code>ENTER</code> in your browser console. These methods include <code>test()</code>, <code>exec()</code>, and <code>toString()</code>. </p>
<p>Apart from those three, some methods take regular expressions as a parameter. But it is better to discuss them under "string methods for working with regular expressions" because, at their core, they are string methods that take regular expressions as a parameter.</p>
<p>Let’s take a look at what <code>test()</code>, <code>exec()</code>, and <code>toString()</code> do.</p>
<h4 id="heading-the-test-method">The <code>test()</code> Method</h4>
<p>The <code>test()</code> method tests for a match between a regular expression and the test string and returns a boolean as the result. If there's a match, it returns <code>true</code>, and if there's no match, it returns <code>false</code>.</p>
<p>In the example below, there's a match for the pattern <code>/freeCodeCamp/</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/freeCodeCamp/</span>;
<span class="hljs-keyword">const</span> testStr =
  <span class="hljs-string">"freeCodeCamp doesn't charge you any money, that's why it's called freeCodeCamp."</span>;

<span class="hljs-built_in">console</span>.log(re.test(testStr)); <span class="hljs-comment">//true</span>
</code></pre>
<p>But in the example below, there's no match for the pattern <code>/fcc/</code>, so the <code>test()</code> method returns <code>false</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/fcc/</span>;
<span class="hljs-keyword">const</span> testStr =
  <span class="hljs-string">"freeCodeCamp doesn't charge you any money, that's why it's called freeCodeCamp."</span>;

<span class="hljs-built_in">console</span>.log(re.test(testStr)); <span class="hljs-comment">//false</span>
</code></pre>
<p>Apart from testing random patterns against a string, the <code>test()</code> method can be useful in form validation. </p>
<h4 id="heading-the-exec-method">The <code>exec()</code> Method</h4>
<p>The <code>exec()</code> method executes a search for a match in a test string and returns an array containing a piece of detailed information about the first match. If there's no match, it returns <code>null</code>.</p>
<p>That detailed information contains the <strong>first match</strong>, <strong>the index of the match</strong>, <strong>captured groups</strong> (if any), and the <strong>length</strong>.</p>
<p>Here's an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/freeCodeCamp/</span>;
<span class="hljs-keyword">const</span> testStr =
  <span class="hljs-string">"freeCodeCamp doesn't charge you any money, that's why it's called freeCodeCamp."</span>;

<span class="hljs-built_in">console</span>.log(re.exec(testStr));
</code></pre>
<p>And here’s a screenshot of the result:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/exec-res.png" alt="exec-res" width="600" height="400" loading="lazy"></p>
<p>If you want to make the <code>exec()</code> method return all the matches, you can use the <code>g</code> flag on the pattern and then loop through with a <code>while</code> loop:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/freeCodeCamp/g</span>;
<span class="hljs-keyword">const</span> testStr =
  <span class="hljs-string">"freeCodeCamp is a great place to start learning to code from scratch. freeCodeCamp doesn't charge you any money, that's why it's called freeCodeCamp."</span>;

<span class="hljs-keyword">let</span> match;

<span class="hljs-keyword">while</span> ((match = re.exec(testStr)) !== <span class="hljs-literal">null</span>) {
  <span class="hljs-built_in">console</span>.log(match[<span class="hljs-number">0</span>]);
}
</code></pre>
<p>Here's what the result looks like in the console:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/exec-multi-res.png" alt="exec-multi-res" width="600" height="400" loading="lazy"></p>
<p>You can go further by accessing the index of the matches this way:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/freeCodeCamp/g</span>;
<span class="hljs-keyword">const</span> testStr =
  <span class="hljs-string">"freeCodeCamp is a great place to start learning to code from scratch. freeCodeCamp doesn't charge you any money, that's why it's called freeCodeCamp."</span>;

<span class="hljs-keyword">let</span> match;

<span class="hljs-keyword">while</span> ((match = re.exec(testStr)) !== <span class="hljs-literal">null</span>) {
  <span class="hljs-built_in">console</span>.log(match[<span class="hljs-number">0</span>]);

  <span class="hljs-comment">//   Access the indices of the matches</span>
  <span class="hljs-built_in">console</span>.log(match.index);
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/exec-indices-res.png" alt="exec-indices-res" width="600" height="400" loading="lazy"></p>
<p>If there's no match, <code>exec()</code> returns null:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/fcc/</span>;
<span class="hljs-keyword">const</span> testStr =
  <span class="hljs-string">"freeCodeCamp doesn't charge you any money, that's why it's called freeCodeCamp."</span>;

<span class="hljs-built_in">console</span>.log(re.exec(testStr)); <span class="hljs-comment">//null</span>
</code></pre>
<h4 id="heading-the-tostring-method">The <code>toString()</code> Method</h4>
<p>The <code>toString()</code> method converts a regex pattern to a string. In JavaScript, the <code>toString()</code> method is in every object. Regular expressions are treated as an object behind the scenes, that's why you can create them with the <code>new</code> keyword.</p>
<p>Using this method on a regex pattern converts the pattern to a string:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> pattern = <span class="hljs-regexp">/freeCodeCamp/</span>;
<span class="hljs-keyword">const</span> strPattern = pattern.toString();

<span class="hljs-built_in">console</span>.log(strPattern, <span class="hljs-keyword">typeof</span> strPattern); <span class="hljs-comment">// /freeCodeCamp/ string</span>
</code></pre>
<p>Even if you create the pattern with the <code>RegExp()</code> constructor, you get the result the same way:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> pattern = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(<span class="hljs-string">'freeCodeCamp'</span>);
<span class="hljs-keyword">const</span> strPattern = pattern.toString();

<span class="hljs-built_in">console</span>.log(strPattern, <span class="hljs-keyword">typeof</span> strPattern); <span class="hljs-comment">// /freeCodeCamp/ string</span>
</code></pre>
<p>And if you have a flag in the pattern, it would be returned as a part of the string:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> pattern = <span class="hljs-regexp">/freeCodeCamp/gi</span>;
<span class="hljs-keyword">const</span> strPattern = pattern.toString();

<span class="hljs-built_in">console</span>.log(strPattern, <span class="hljs-keyword">typeof</span> strPattern); <span class="hljs-comment">// /freeCodeCamp/gi string</span>
</code></pre>
<h3 id="heading-properties-of-the-regexp-constructor">Properties of the <code>RegExp()</code> Constructor</h3>
<p>The properties of the <code>RegExp()</code> constructor are defined on the <code>RegExp.prototype</code>. They include:</p>
<ul>
<li><code>RegExp.prototype.global</code></li>
<li><code>RegExp.prototype.source</code></li>
<li><code>RegExp.prototype.flags</code></li>
<li><code>RegExp.prototype.multiline</code></li>
<li><code>RegExp.prototype.ignoreCase</code></li>
<li><code>RegExp.prototype.dotAll</code></li>
<li><code>RegExp.prototype.sticky</code></li>
<li><code>RegExp.prototype.unicode</code></li>
</ul>
<p>In short, there are the <code>global</code>, <code>source</code>, <code>flags</code>, <code>multiline</code>, <code>ignoreCase</code>, <code>dotAll</code>, <code>sticky</code>, and <code>unicode</code>.</p>
<p>Most of the properties check whether a certain flag is used or not. Let's take a look at how each of the properties works. </p>
<h4 id="heading-the-global-property">The <code>global</code> Property</h4>
<p>The global property checks whether the <code>g</code> flag is used with a regex pattern or not. If the pattern has the <code>g</code> flag, it returns <code>true</code>, otherwise it returns <code>false</code>. </p>
<p>Remember the <code>global</code> (<code>g</code>) flag indicates that the regex pattern should not just return the first match but all the matches.</p>
<p>Here's how the <code>global</code> property works in code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> re1 = <span class="hljs-regexp">/freeCodeCamp/g</span>;
<span class="hljs-keyword">const</span> re2 = <span class="hljs-regexp">/freeCodeCamp/</span>;
<span class="hljs-keyword">const</span> re3 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(<span class="hljs-string">'freeCodeCamp'</span>);
<span class="hljs-keyword">const</span> re4 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(<span class="hljs-string">'freeCodeCamp'</span>, <span class="hljs-string">'g'</span>);

<span class="hljs-built_in">console</span>.log(re1.global); <span class="hljs-comment">//true</span>
<span class="hljs-built_in">console</span>.log(re2.global); <span class="hljs-comment">//false</span>
<span class="hljs-built_in">console</span>.log(re3.global); <span class="hljs-comment">//false</span>
<span class="hljs-built_in">console</span>.log(re4.global); <span class="hljs-comment">//true</span>
</code></pre>
<h4 id="heading-the-flag-property">The <code>flag</code> Property</h4>
<p>The flag property returns the flags you use in the regex pattern in alphabetical order. That is, <code>g</code> before <code>i</code>, <code>i</code> before <code>m</code>, <code>m</code> before <code>y</code>, and so on.</p>
<p>In the code below, you can see that the <code>g</code> flag comes before <code>i</code>, and <code>m</code> comes before <code>y</code>: </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> re1 = <span class="hljs-regexp">/freeCodeCamp/gi</span>;
<span class="hljs-keyword">const</span> re2 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(<span class="hljs-string">'freeCodeCamp'</span>, <span class="hljs-string">'my'</span>);

<span class="hljs-built_in">console</span>.log(re1.flags); <span class="hljs-comment">//gi</span>
<span class="hljs-built_in">console</span>.log(re2.flags); <span class="hljs-comment">//my</span>
</code></pre>
<h4 id="heading-the-source-property">The <code>source</code> Property</h4>
<p>The <code>source</code> property returns the regex pattern as a string. So, it acts like the <code>toString()</code> method.</p>
<p>The difference between the <code>source</code> property and the <code>toString()</code> method is that the <code>source</code> property excludes the flag you use with the pattern. Also, the <code>source</code> property does not show the literal forward slashes you use for creating the regex.</p>
<p>In the code below, you can see the forward slashes don’t get printed, the flags are omitted too, and the <code>type</code> is a string:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> re1 = <span class="hljs-regexp">/freeCodeCamp/gi</span>;
<span class="hljs-keyword">const</span> re2 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(<span class="hljs-string">'freeCodeCamp'</span>, <span class="hljs-string">'my'</span>);

<span class="hljs-keyword">const</span> re1Source = re1.source;
<span class="hljs-keyword">const</span> re2Source = re2.source;

<span class="hljs-built_in">console</span>.log(re1Source, <span class="hljs-keyword">typeof</span> re1Source); <span class="hljs-comment">// freeCodeCamp string</span>
<span class="hljs-built_in">console</span>.log(re2Source, <span class="hljs-keyword">typeof</span> re2Source); <span class="hljs-comment">// freeCodeCamp string</span>
</code></pre>
<h4 id="heading-the-multiline-property">The <code>multiline</code> Property</h4>
<p>The <code>multiline</code> flag is another boolean property of the <code>RegExp()</code> constructor. It specifies whether the <code>multiline</code> flag is used with the pattern or not by returning <code>true</code> or <code>false</code>. </p>
<p>Remember the <code>multiline</code> (<code>m</code>) flag indicates that the test string should be treated as a text that has more than one line.</p>
<p>Here's how the <code>multiline</code> property works in action:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> re1 = <span class="hljs-regexp">/freeCodeCamp/gi</span>;
<span class="hljs-keyword">const</span> re2 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(<span class="hljs-string">'freeCodeCamp'</span>, <span class="hljs-string">'my'</span>);

<span class="hljs-keyword">const</span> re1Source = re1.multiline;
<span class="hljs-keyword">const</span> re2Source = re2.multiline;

<span class="hljs-built_in">console</span>.log(re1Source); <span class="hljs-comment">//false</span>
<span class="hljs-built_in">console</span>.log(re2Source); <span class="hljs-comment">// true</span>
</code></pre>
<h4 id="heading-the-ignorecase-property">The ignoreCase Property</h4>
<p>The <code>ignoreCase</code> property specifies whether the case-insensitive flag (<code>i</code>) is used in the regex pattern. It returns <code>true</code> if you use the <code>i</code> flag and <code>false</code> if you don’t use it.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> re1 = <span class="hljs-regexp">/freeCodeCamp/i</span>;
<span class="hljs-keyword">const</span> re2 = <span class="hljs-regexp">/freeCodeCamp/</span>;
<span class="hljs-keyword">const</span> re3 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(<span class="hljs-string">'freeCodeCamp'</span>, <span class="hljs-string">'i'</span>);
<span class="hljs-keyword">const</span> re4 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(<span class="hljs-string">'freeCodeCamp'</span>);

<span class="hljs-built_in">console</span>.log(re1.ignoreCase); <span class="hljs-comment">//true</span>
<span class="hljs-built_in">console</span>.log(re2.ignoreCase); <span class="hljs-comment">// false</span>
<span class="hljs-built_in">console</span>.log(re3.ignoreCase); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(re4.ignoreCase); <span class="hljs-comment">// false</span>
</code></pre>
<h4 id="heading-the-unicode-property">The <code>Unicode</code> Property</h4>
<p>The <code>unicode</code> property helps you check whether the Unicode (<code>u</code>) flag is used in the regex pattern or not. If it finds the <code>u</code> flag, it returns <code>true</code>, otherwise it returns <code>false</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> re1 = <span class="hljs-regexp">/\u{1F1F3}\u{1F1EC}/u</span>; <span class="hljs-comment">//matches the Nigerian flag emoji</span>
<span class="hljs-keyword">const</span> re2 = <span class="hljs-regexp">/\u{1F1F3}\u{1F1EC}/</span>;
<span class="hljs-keyword">const</span> re3 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(<span class="hljs-string">'\u{1F1F3}\u{1F1EC}'</span>, <span class="hljs-string">'u'</span>);
<span class="hljs-keyword">const</span> re4 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(<span class="hljs-string">'\u{1F1F3}\u{1F1EC}'</span>);

<span class="hljs-built_in">console</span>.log(re1.unicode); <span class="hljs-comment">//true</span>
<span class="hljs-built_in">console</span>.log(re2.unicode); <span class="hljs-comment">// false</span>
<span class="hljs-built_in">console</span>.log(re3.unicode); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(re4.unicode); <span class="hljs-comment">// false</span>
</code></pre>
<h4 id="heading-the-sticky-property">The <code>sticky</code> Property</h4>
<p>The sticky property indicates whether the sticky (<code>y</code>) flag is set in the regular expression or not. Even though that's what it does, it's still a bit tricky to understand because of the <code>lastIndex</code> property.</p>
<p>When the <code>y</code> flag is set, the regex engine in use will attempt to match the pattern starting at the exact position specified by the <code>lastIndex</code> property (without using the <code>g</code> flag). If a match is found, the <code>lastIndex</code> property is updated to the position immediately after the end of the match.</p>
<p>To help you understand that better, here's a code snippet with comments:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/xyz/y</span>;
<span class="hljs-keyword">const</span> str = <span class="hljs-string">'xyzxyz'</span>;

re.lastIndex = <span class="hljs-number">0</span>;
<span class="hljs-built_in">console</span>.log(re.test(str)); <span class="hljs-comment">// true – there's a match at index 0 to 2</span>
<span class="hljs-built_in">console</span>.log(re.lastIndex); <span class="hljs-comment">// 3</span>

re.lastIndex = <span class="hljs-number">1</span>;
<span class="hljs-built_in">console</span>.log(re.test(str)); <span class="hljs-comment">// false – no match at the specified index</span>
<span class="hljs-built_in">console</span>.log(re.lastIndex); <span class="hljs-comment">// 0 – resets to 0 because there's no match at the specified index</span>

re.lastIndex = <span class="hljs-number">3</span>;
<span class="hljs-built_in">console</span>.log(re.test(str)); <span class="hljs-comment">// true – there's a match at index 3 to 5</span>
<span class="hljs-built_in">console</span>.log(re.lastIndex); <span class="hljs-comment">// 6</span>

re.lastIndex = <span class="hljs-number">6</span>;
<span class="hljs-built_in">console</span>.log(re.test(str)); <span class="hljs-comment">// false</span>
<span class="hljs-built_in">console</span>.log(re.lastIndex); <span class="hljs-comment">// 0 – resets to 0 because there's no match at the specified index</span>
</code></pre>
<p><strong>N.B.</strong>: The <code>dotAll</code> property works with the wildcard (<code>.</code>) metacharacter. Due to that, you will see how it works in detail in the chapter on metacharacters. Also, <code>hasIndices</code> works with captures. So, you will see how to use it under the chapter on grouping and capturing.</p>
<h3 id="heading-string-methods-for-working-with-regular-expressions">String Methods for Working with Regular Expressions</h3>
<p>JavaScript provides some inbuilt methods for working with strings. Some of these methods take regular expressions as a parameter. These methods include <code>match()</code>, <code>matchAll()</code>, <code>replace()</code>, <code>replaceAll()</code>, <code>split()</code>, and <code>search()</code>.</p>
<p>Let's look at each of them one by one.</p>
<h4 id="heading-the-search-method">The <code>search()</code> Method</h4>
<p>The <code>search()</code> method searches for the match of a regular expression in a string and returns the index of the match. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr =
  <span class="hljs-string">"fCC is the abbreviation for freeCodeCamp. freeCodeCamp doesn't charge you any money, that's why it's called freeCodeCamp. Learn to code for free today."</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/freeCodeCamp/</span>;
<span class="hljs-keyword">const</span> searchFCC = myStr.search(re);

<span class="hljs-built_in">console</span>.log(searchFCC); <span class="hljs-comment">//28</span>
</code></pre>
<p>If the <code>search()</code> method finds no match, it returns <code>-1</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr =
  <span class="hljs-string">"fCC is the abbreviation for freeCodeCamp. freeCodeCamp doesn't charge you any money, that's why it's called freeCodeCamp. Learn to code for free today."</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/FCC/</span>;
<span class="hljs-keyword">const</span> searchFCC = myStr.search(re);

<span class="hljs-built_in">console</span>.log(searchFCC); <span class="hljs-comment">//-1</span>
</code></pre>
<p>You might be thinking using the <code>g</code> flag with the pattern would return the indices of all the matches, but this isn't the case. The <code>g</code> flag does not affect the <code>search()</code> method:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr =
  <span class="hljs-string">"fCC is the abbreviation for freeCodeCamp. freeCodeCamp doesn't charge you any money, that's why it's called freeCodeCamp. Learn to code for free today."</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/freeCodeCamp/g</span>; <span class="hljs-comment">//pattern with g flag</span>
<span class="hljs-keyword">const</span> searchFCC = myStr.search(re);

<span class="hljs-built_in">console</span>.log(searchFCC); <span class="hljs-comment">//28</span>
</code></pre>
<p>If you want to get the indices of all the matches, you should use the <code>match()</code> or <code>matchAll()</code> method.</p>
<h4 id="heading-the-match-method">The <code>match()</code> Method</h4>
<p>The <code>match()</code> method lets you specify a regex pattern as the parameter, then it runs through the string you use it against and returns an array containing the substring(s) that match the regex pattern.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> my_str = <span class="hljs-string">'freeCodeCamp'</span>;
match = my_str.match(<span class="hljs-regexp">/free/</span>);

<span class="hljs-built_in">console</span>.log(match); <span class="hljs-comment">// [ 'free', index: 0, input: 'freeCodeCamp', groups: undefined ]</span>
</code></pre>
<p>You can also separate the regex pattern into a separate variable:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> my_str = <span class="hljs-string">'freeCodeCamp'</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/free/</span>;
<span class="hljs-keyword">const</span> match = my_str.match(re);

<span class="hljs-built_in">console</span>.log(match); <span class="hljs-comment">// [ 'free', index: 0, input: 'freeCodeCamp', groups: undefined ]</span>
</code></pre>
<p>If <code>match()</code> finds multiple matches, it returns all of them in the array, provided you use the <code>g</code> flag in the pattern: </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> my_str =
  <span class="hljs-string">"freeCodeCamp doesn't charge you any money, that's why it's called freeCodeCamp. Learn to code for free today."</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/free/g</span>;
<span class="hljs-keyword">const</span> match = my_str.match(re);

<span class="hljs-built_in">console</span>.log(match); <span class="hljs-comment">// ['free', 'free', 'free']</span>
</code></pre>
<p>If you expand the array, this is what it looks like:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/match-method-matches.png" alt="match-method-matches" width="600" height="400" loading="lazy"></p>
<p>Since the result is an array, you should probably use <code>console.table()</code> instead of <code>console.log()</code> so you can see the indices of the matches:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> my_str =
  <span class="hljs-string">"freeCodeCamp doesn't charge you any money, that's why it's called freeCodeCamp. Learn to code for free today."</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/free/g</span>;
<span class="hljs-keyword">const</span> match = my_str.match(re);

<span class="hljs-built_in">console</span>.table(match);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/match-console-table.png" alt="match-console-table" width="600" height="400" loading="lazy"></p>
<p>If the <code>match()</code> method finds no match, it returns <code>null</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> my_str = <span class="hljs-string">'freeCodeCamp'</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/ref/</span>;
<span class="hljs-keyword">const</span> match = my_str.match(re);

<span class="hljs-built_in">console</span>.log(match); <span class="hljs-comment">// null</span>
</code></pre>
<h4 id="heading-the-matchall-method">The <code>matchAll()</code> Method</h4>
<p><code>matchAll()</code> is a hybrid of the <code>match()</code> method. It returns an iterator of all the substrings that match the regular expressions you provide. This means you have to use it with the <code>global</code> (<code>g</code>) flag.</p>
<p>Because it returns the iterator of all matches, <code>matchAll()</code> is a great option for looping through the matches of regular expressions. </p>
<p>An alternative to iterating through the matches of a regular expression is using the <code>exec()</code> method and <code>g</code> flag, then looping with a <code>while</code> loop this way:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> my_str =
  <span class="hljs-string">"freeCodeCamp doesn't charge you any money, that's why it's called freeCodeCamp. Learn to code for free today."</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/free/g</span>;

<span class="hljs-keyword">let</span> match;
<span class="hljs-keyword">while</span> ((match = re.exec(my_str))) {
  <span class="hljs-built_in">console</span>.log(match[<span class="hljs-number">0</span>]); <span class="hljs-comment">//</span>
}

<span class="hljs-comment">// free</span>
<span class="hljs-comment">// free</span>
<span class="hljs-comment">// free</span>
</code></pre>
<p>With the <code>matchAll()</code> method, you don’t need the <code>exec()</code> and <code>while</code> loop. All you need is a <code>for…of</code> loop to get the matches:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> my_str =
  <span class="hljs-string">"freeCodeCamp doesn't charge you any money, that's why it's called freeCodeCamp. Learn to code for free today."</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/free/g</span>;
<span class="hljs-keyword">const</span> matches = my_str.matchAll(re);

<span class="hljs-built_in">console</span>.log(matches); <span class="hljs-comment">// RegExpStringIterator {}</span>

<span class="hljs-comment">//loop through the matches with a for...of loop</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> match <span class="hljs-keyword">of</span> matches) {
  <span class="hljs-built_in">console</span>.log(match);
}
</code></pre>
<p>This returns each <code>match</code>, their index, the test string, the length, and groups in their respective arrays:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/matchAll-console.png" alt="matchAll-console" width="600" height="400" loading="lazy"></p>
<p>You can modify the console log to get only the matches and their index this way:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> my_str =
  <span class="hljs-string">"freeCodeCamp doesn't charge you any money, that's why it's called freeCodeCamp. Learn to code for free today."</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/free/g</span>;
<span class="hljs-keyword">const</span> matches = my_str.matchAll(re);

<span class="hljs-built_in">console</span>.log(matches); <span class="hljs-comment">// RegExpStringIterator {}</span>

<span class="hljs-comment">//loop through the matches with a for...of loop</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> match <span class="hljs-keyword">of</span> matches) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Found a match <span class="hljs-subst">${match[<span class="hljs-number">0</span>]}</span> at index <span class="hljs-subst">${match.index}</span>`</span>);
}

<span class="hljs-comment">/*
Output:
Found a match free at index 0
Found a match free at index 66
Found a match free at index 98
*/</span>
</code></pre>
<p>You can also use the <code>Array.from()</code> method to do the same thing:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> my_str =
  <span class="hljs-string">"freeCodeCamp doesn't charge you any money, that's why it's called freeCodeCamp. Learn to code for free today."</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/free/g</span>;

<span class="hljs-built_in">Array</span>.from(my_str.matchAll(re), <span class="hljs-function">(<span class="hljs-params">match</span>) =&gt;</span>
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Found a match <span class="hljs-subst">${match[<span class="hljs-number">0</span>]}</span> at index <span class="hljs-subst">${match.index}</span>`</span>)
);

<span class="hljs-comment">/*
Output:
Found a match free at index 0
Found a match free at index 66
Found a match free at index 98
*/</span>
</code></pre>
<p>If the <code>matchAll()</code> method finds no match, it returns an empty iterator. And if you decide to loop through that empty iterator, there'll be nothing to see in the console.</p>
<h4 id="heading-the-replace-method">The <code>replace()</code> Method</h4>
<p>The <code>replace()</code> method does what its name implies. It searches for matches of a specified string or regular expression in a string and replaces them with the specified replacement string. It returns a new string with the replacements applied.</p>
<p>The <code>replace()</code> method is not as straightforward as <code>match()</code> and <code>matchAll()</code> because it accepts two parameters – a regular expression and the replacement string. Any substring of the test string that matches the regular expressions is then replaced with the replacement string.</p>
<p>If the regular expression does not include the global (<code>g</code>) flag, only the first match is replaced:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr =
  <span class="hljs-string">'Elephants are very large animals. They are large to the extent that they can uproot a large tree.'</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/large/</span>;
<span class="hljs-keyword">const</span> replaceLarge = myStr.replace(re, <span class="hljs-string">'massive'</span>);

<span class="hljs-built_in">console</span>.log(replaceLarge); <span class="hljs-comment">// Elephants are very massive animals. They are large to the extent that they can uproot a large tree.</span>
</code></pre>
<p>If you use the <code>g</code> flag in the pattern, all the matches are replaced:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr =
  <span class="hljs-string">'Elephants are very large animals. They are large to the extent that they can uproot a large tree.'</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/large/g</span>;
<span class="hljs-keyword">const</span> replaceLarge = myStr.replace(re, <span class="hljs-string">'massive'</span>);

<span class="hljs-built_in">console</span>.log(replaceLarge); <span class="hljs-comment">// Elephants are very massive animals. They are massive to the extent that they can uproot a massive tree.</span>
</code></pre>
<h4 id="heading-the-replaceall-method">The <code>replaceAll()</code> Method</h4>
<p>The <code>replaceAll()</code> method is relatively new because it became available in ECMAScript 2021. It is a hybrid of <code>replace()</code>.</p>
<p>Both <code>replace()</code> and <code>replaceAll()</code> do the same thing by taking a regular expression and a replacement string as parameters, and replacing all matches with the specified replacement string. </p>
<p>But unlike <code>replace()</code> which will only replace the first match if you don’t use the <code>g</code> flag, <code>replaceAll()</code> replaces all the matches by default:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr =
  <span class="hljs-string">'Elephants are very large animals. They are large to the extent that they can uproot a large tree.'</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/large/g</span>;
<span class="hljs-keyword">const</span> replaceLarge = myStr.replaceAll(re, <span class="hljs-string">'massive'</span>);

<span class="hljs-built_in">console</span>.log(replaceLarge); <span class="hljs-comment">// Elephants are very massive animals. They are massive to the extent that they can uproot a massive tree.</span>
</code></pre>
<p>If you don’t use the <code>g</code> flag with <code>replaceAll()</code>, it throws a <code>TypeError</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr =
  <span class="hljs-string">'Elephants are very large animals. They are large to the extent that they can uproot a large tree.'</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/large/</span>;
<span class="hljs-keyword">const</span> replaceLarge = myStr.replaceAll(re, <span class="hljs-string">'massive'</span>);

<span class="hljs-built_in">console</span>.log(replaceLarge); <span class="hljs-comment">// Uncaught TypeError: String.prototype.replaceAll called with a non-global RegExp argument</span>
<span class="hljs-comment">//    at String.replaceAll (&lt;anonymous&gt;)</span>
</code></pre>
<h4 id="heading-the-split-method">The <code>split()</code> Method</h4>
<p>The <code>split()</code> method takes a string or regex and splits the string you use it against into an array based on the string or regex you pass into it. The <code>split()</code> method also takes an optional <code>limit</code> parameter, a positive number. When you specify the <code>limit</code>, the splitting stops at that limit.</p>
<p>Wherever the <code>split()</code> finds a match, it creates a new item in the array. Here's how it works:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr = <span class="hljs-string">"Codes don't lie. You're the one doing something wrong."</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/\s/</span>; <span class="hljs-comment">// "\s" means white space - spacebar, backspace, tab, ENTER.</span>

<span class="hljs-keyword">const</span> splitedStr = myStr.split(re);
<span class="hljs-built_in">console</span>.log(splitedStr);

<span class="hljs-comment">/* 
Output:
[
  'Codes',  "don't",
  'lie.',   "You're",
  'the',    'one',
  'doing',  'something',
  'wrong.'
]
*/</span>
</code></pre>
<p>Here's how to use the <code>split()</code> method with the <code>limit</code> parameter:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr = <span class="hljs-string">"Codes don't lie. You're the one doing something wrong."</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/\s/</span>; <span class="hljs-comment">// "\s" means white space - spacebar, backspace, tab, ENTER.</span>

<span class="hljs-keyword">const</span> splitedStr = myStr.split(re, <span class="hljs-number">5</span>); <span class="hljs-comment">// 5 is the limit here</span>
<span class="hljs-built_in">console</span>.log(splitedStr);

<span class="hljs-comment">/*
output: [ 'Codes', "don't", 'lie.', "You're", 'the' ]
*/</span>
</code></pre>
<h3 id="heading-how-to-match-literal-characters-in-javascript-regular-expressions">How to Match Literal Characters in JavaScript Regular Expressions</h3>
<p>As I pointed out earlier, literal characters are texts or strings you will write patterns for as they are.</p>
<p>If you want to match the text <code>hello</code>, <code>/hello/</code> should be your pattern. You can then use the <code>i</code> flag with it to match both <code>hello</code> and <code>Hello</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> testString = <span class="hljs-string">'hello'</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/hello/</span>;
<span class="hljs-keyword">const</span> re2 = <span class="hljs-regexp">/hello/i</span>;

<span class="hljs-built_in">console</span>.log(re.test(testString)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(re2.test(testString)); <span class="hljs-comment">// true</span>
</code></pre>
<p>If you want to match <code>freeCodeCamp</code>, the pattern should be just that. You can also create a pattern that matches <code>freeCodeCamp</code> in any case:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> testString = <span class="hljs-string">'freeCodeCamp'</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/freeCodeCamp/</span>;
<span class="hljs-keyword">const</span> re2 = <span class="hljs-regexp">/freeCodeCamp/i</span>; <span class="hljs-comment">// match freeCodeCamp in any case</span>

<span class="hljs-built_in">console</span>.log(re.test(testString)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(re2.test(testString)); <span class="hljs-comment">// true</span>
</code></pre>
<p>You can also match digits using literal characters:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> num = <span class="hljs-number">10234</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/2/</span>;

<span class="hljs-built_in">console</span>.log(re.test(num)); <span class="hljs-comment">//true</span>
</code></pre>
<h3 id="heading-how-to-use-character-sets-in-javascript-regular-expressions">How to Use Character Sets in JavaScript Regular Expressions</h3>
<p>As a reminder, a character set is a group of characters enclosed in square brackets. They provide a way to specify a set of characters from which the regex engine can match a single character at a specific position in a test string. </p>
<p>Character sets allow you to specify a range of characters, individual characters, or a combination of both.</p>
<p>Here are common examples of popular character sets in regular expressions:</p>
<ul>
<li><code>[abc]</code>: matches either <code>a</code>, <code>b</code>, or <code>c</code></li>
<li><code>[aeiou]</code>: matches any vowel character</li>
<li><code>[a-z]</code>: matches any lowercase letter from <code>a</code> to <code>z</code></li>
<li><code>[A-Z]</code>: matches any uppercase letter from <code>A</code> to <code>Z</code></li>
<li><code>[0-9]</code>: matches any digit from 0 to 9</li>
</ul>
<p>Let's look at how to match each of the above character sets in JavaScript regular expressions:</p>
<pre><code class="lang-js"><span class="hljs-comment">// uppercase character set</span>
<span class="hljs-keyword">const</span> hcaseRe = <span class="hljs-regexp">/[A-Z]/</span>;
<span class="hljs-keyword">const</span> hcaseStr = <span class="hljs-string">'freeCodeCamp is cool'</span>;

<span class="hljs-built_in">console</span>.log(hcaseRe.test(hcaseStr)); <span class="hljs-comment">//true</span>

<span class="hljs-comment">// vowels character set</span>
<span class="hljs-keyword">const</span> vowelsRe = <span class="hljs-regexp">/[aeiou]/</span>;
<span class="hljs-keyword">const</span> vowelsStr = <span class="hljs-string">'Imagine how pronunciation would have been without vowels'</span>;

<span class="hljs-built_in">console</span>.log(vowelsRe.test(vowelsStr)); <span class="hljs-comment">//true</span>

<span class="hljs-comment">// [abc] character set</span>
<span class="hljs-keyword">const</span> abcSetRe = <span class="hljs-regexp">/[abc]/</span>;
<span class="hljs-keyword">const</span> abcSetStr = <span class="hljs-string">'freeCodeCamp is totally free'</span>;

<span class="hljs-built_in">console</span>.log(abcSetRe.test(abcSetStr)); <span class="hljs-comment">//true</span>

<span class="hljs-comment">// number character set</span>
<span class="hljs-keyword">const</span> numRe = <span class="hljs-regexp">/[0-9]/</span>;
<span class="hljs-keyword">const</span> numStr = <span class="hljs-string">'Thank God for Arabic numerals 0 to 9.'</span>;

<span class="hljs-built_in">console</span>.log(numRe.test(numStr)); <span class="hljs-comment">//true</span>
</code></pre>
<h2 id="heading-chapter-5-metacharacters-quantifiers-repeated-matches-and-optional-matches">Chapter 5: Metacharacters, Quantifiers, Repeated Matches, and Optional Matches</h2>
<h3 id="heading-what-are-metacharacters">What are Metacharacters?</h3>
<p>In regular expressions, metacharacters are characters that have special meanings beyond their literal meaning. </p>
<p>Metacharacters are the backbone of regular expressions. They serve as the building blocks for constructing better regex patterns and defining the behavior of the regular expression engine you're using, but with an extra learning curve.</p>
<p>This part of the book is where you will learn about topics such as:</p>
<ul>
<li>Anchors</li>
<li>Word boundaries</li>
<li>How to specify character ranges</li>
<li>How to match every occurrence with the wildcard</li>
<li>Alternation</li>
<li>Greediness and laziness of regular expressions and how to prevent greediness</li>
</ul>
<p>And lots more.</p>
<p>If you want to match any metacharacter as a literal character, you have to escape it with a backslash (<code>\</code>). And if there's a metacharacter represented by a word, you have to escape it with the backslash too. So, the backslash is also a separate metacharacter.</p>
<p>There's a metacharacter to negate most metacharacters. For instance, <code>\b</code> and <code>\s</code> represent the word boundary and space metacharacters. If you want to negate them, you can use <code>\B</code> and <code>\S</code> respectively. That's the pattern most metacharacters follow – the small letter is the metacharacter and the capital letter negates it.</p>
<p>Metacharacters are categorized into single and double metacharacters. As the name implies, single metacharacters have a "single" character and double metacharacters have a "double" character. </p>
<p>Most metacharacters are also called shorthand character classes. As we look at each metacharacter, you will see whether it is a single or double metacharacter.</p>
<h3 id="heading-the-word-and-non-word-metacharacters">The Word and Non-word Metacharacters</h3>
<p>Represented by <code>\w</code>, the word metacharacter is a shorthand character class that matches all word characters. Word characters are alphanumeric characters and underscores. So, they are <code>a-z</code>, A-Z, <code>0-9</code>, and underscore (<code>_</code>).</p>
<p>Here's what happens when you use <code>\w</code> in a regex tester:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/w-matches.png" alt="w-matches" width="600" height="400" loading="lazy"></p>
<p>And here’s how it works in JavaScript:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> testStr =
  <span class="hljs-string">'Every alphanumeric character (a to z and 0 to 9) and underscore (_) is a word character'</span>;
<span class="hljs-keyword">const</span> wordCharacterRe = <span class="hljs-regexp">/\w/g</span>;

<span class="hljs-built_in">console</span>.log(testStr.match(wordCharacterRe));
</code></pre>
<p>Since word characters are alphanumeric characters and underscores, you can simulate the <code>\w</code> metacharacter by putting all the examples in a character set:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> testStr =
  <span class="hljs-string">'Every alphanumeric character (a to z and 0 to 9) and underscore (_) is a word character'</span>;
<span class="hljs-keyword">const</span> wordCharacterRe = <span class="hljs-regexp">/[a-z A-Z 0-9_]/g</span>;

<span class="hljs-built_in">console</span>.log(testStr.match(wordCharacterRe));
</code></pre>
<p>The non-word metacharacter is the opposite of the word metacharacter and it is represented by an escaped capital letter W (<code>\W</code>). </p>
<p>The non-word metacharacter matches every other character apart from alphanumeric characters and the underscore. That includes spaces, punctuation marks, and symbols:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/w-matches-1.png" alt="w-matches-1" width="600" height="400" loading="lazy"></p>
<p>Here it is in action in some JavaScript code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> testStr =
  <span class="hljs-string">'Every character apart from alphanumeric characters (a to z and 0 to 9) and underscore (_) is a non-word character'</span>;
<span class="hljs-keyword">const</span> nonWordCharacterRe = <span class="hljs-regexp">/\W/g</span>;

<span class="hljs-built_in">console</span>.log(testStr.match(nonWordCharacterRe));
</code></pre>
<p>Since you can represent the word metacharacter by putting all the characters in a character set, you may be wondering how you can do the same for the non-word metacharacter. </p>
<p>That's where the negated character set comes in. The caret (<code>^</code>) is used for negation. It is one of the two <strong>anchor metacharacters</strong>, which we'll look at next.</p>
<h3 id="heading-the-anchor-metacharacters">The Anchor Metacharacters</h3>
<p>Caret (<code>^</code>) and dollar sign (<code>$</code>) are the two anchor metacharacters. They are both single metacharacters.</p>
<p>The caret anchors the regex pattern to the start of a line or string, so you can call it a "start of line anchor". </p>
<p>For example, if you want to match the text "freeCodeCamp" and you want to make sure it's at the start of the line or a string, you can use the caret this way:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/fcc-anchor-match.png" alt="fcc-anchor-match" width="600" height="400" loading="lazy"></p>
<p>If the <code>freeCodeCamp</code> text is not at the start of the line, there won't be a match:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/fcc-anchor-no-match.png" alt="fcc-anchor-no-match" width="600" height="400" loading="lazy"></p>
<p>Here are the two cases in JavaScript code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> testStr =
  <span class="hljs-string">"freeCodeCamp doesn't charge you any money. That's why it's called freeCodeCamp because. Learn to code for free today."</span>; <span class="hljs-comment">// has "freeCodeCamp" at the start of the line</span>

<span class="hljs-keyword">const</span> testStr2 =
  <span class="hljs-string">"It's called freeCodeCamp because freeCodeCamp doesn't charge you any money. Learn to code for free today."</span>; <span class="hljs-comment">// does not have "freeCodeCamp" at the start of the line</span>

<span class="hljs-keyword">const</span> startAnchorRe = <span class="hljs-regexp">/^freeCodeCamp/</span>;

<span class="hljs-built_in">console</span>.log(startAnchorRe.test(testStr)); <span class="hljs-comment">//true</span>
<span class="hljs-built_in">console</span>.log(startAnchorRe.test(testStr2)); <span class="hljs-comment">//false</span>
</code></pre>
<p>The dollar sign metacharacter is the opposite of the caret. It anchors the regex pattern to the end of the line or string. So, there will only be a match if the target text is at the end of the line.</p>
<p>To use the <code>$</code> metacharacter, it has to be the last character in your pattern:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/dollar-meta-match.png" alt="dollar-meta-match" width="600" height="400" loading="lazy"></p>
<p>If the target string has more than one line and the target text is at the end of each line, the last one matches:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/dollar-last-match.png" alt="dollar-last-match" width="600" height="400" loading="lazy"></p>
<p>To correct this behavior, you have to use both the <code>g</code> and <code>m</code> flags:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/dollar-multiple-match.png" alt="dollar-multiple-match" width="600" height="400" loading="lazy"></p>
<p>Here are all the cases in JavaScript code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> testStr =
  <span class="hljs-string">"The lion is not the king of the jungle because of its strength, the lion is the king of the jungle because it's never intimidated"</span>;

<span class="hljs-keyword">const</span> testStr2 = <span class="hljs-string">`The lion is not the king of the jungle because of its strength, the lion is the king of the jungle because it's never intimidated

This is another line that ends with intimidated

And this is the last line that ends with intimidated

And this is the last line that ends with intimidated`</span>;

<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/intimidated$/</span>;
<span class="hljs-keyword">const</span> re2 = <span class="hljs-regexp">/intimidated$/gm</span>;

<span class="hljs-built_in">console</span>.log(re.test(testStr)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(re.test(testStr2)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(re2.test(testStr2)); <span class="hljs-comment">// true</span>
</code></pre>
<p>If the target text is not at the end of the line, there won't be any match:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> testStr =
  <span class="hljs-string">"A lion can never be intimidated because it's the king of the jungle"</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/intimidated$/</span>;

<span class="hljs-built_in">console</span>.log(re.test(testStr)); <span class="hljs-comment">// false</span>
</code></pre>
<p>When you use both the dollar and caret metacharacters with the <code>g</code> and <code>m</code> flags, they don’t just match at the start and end of a line, they find the matches at the start and end of each line:</p>
<pre><code class="lang-js"><span class="hljs-comment">//dollar with g and m flags</span>
<span class="hljs-keyword">const</span> testStr1 = <span class="hljs-string">`The lion is not the king of the jungle because of its strength, the lion is the king of the jungle because it's never intimidated

Another line with intimidated

And another line with intimidated`</span>;

<span class="hljs-keyword">const</span> re1 = <span class="hljs-regexp">/intimidated$/gm</span>;
<span class="hljs-keyword">const</span> matches1 = testStr1.match(re1);

<span class="hljs-built_in">console</span>.log(matches1); <span class="hljs-comment">// [ 'intimidated', 'intimidated', 'intimidated' ]</span>

<span class="hljs-comment">// caret with g and m flags</span>
<span class="hljs-keyword">const</span> testStr = <span class="hljs-string">`freeCodeCamp doesn't charge you any money. That's why it's called freeCodeCamp because. Learn to code for free today.

freeCodeCamp starts this line

freeCodeCamp starts this line too
`</span>;

<span class="hljs-keyword">const</span> re2 = <span class="hljs-regexp">/^freeCodeCamp/gm</span>;
<span class="hljs-keyword">const</span> matches2 = testStr.match(re2);

<span class="hljs-built_in">console</span>.log(matches2); <span class="hljs-comment">// [ 'freeCodeCamp', 'freeCodeCamp', 'freeCodeCamp' ]</span>
</code></pre>
<p>As I pointed out earlier, the caret metacharacter is typically used for negating a character set or any other character. With that, you tell the regex engine in use not to match that character or each of the character sets.</p>
<p>For example, if you have the pattern <code>[^a]</code>, then all letters "a" in the test string won't be returned as matches:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/unmatch-As.png" alt="unmatch-As" width="600" height="400" loading="lazy"></p>
<p>If you have the pattern <code>[^aeiou]</code>, all the vowels in the test string won't be returned as matches:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/unmatch-vowels.png" alt="unmatch-vowels" width="600" height="400" loading="lazy"></p>
<p>If you have the pattern <code>[^a-zA-Z0-9_]</code>, that's equivalent to the non-word metacharacter (<code>\W</code>):</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/non-word-char-class.png" alt="non-word-char-class" width="600" height="400" loading="lazy"></p>
<h3 id="heading-the-digit-and-non-digit-metacharacters">The Digit and Non-digit Metacharacters</h3>
<p>The digit metacharacter is represented by <code>\d</code>. You can negate it with <code>\D</code>, so <code>\D</code> is the non-digit metacharacter.</p>
<p><code>\d</code> matches all numbers (0 to 9), so it is a shorthand character class for <code>[0-9]</code>. So, if you have a string and you want to extract the numbers from it, you can use the <code>\d</code> metacharacter. But you have to use it with the <code>g</code> flag so it matches every number in the test string:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/Screenshot-2023-07-25-at-12.27.21.png" alt="Screenshot-2023-07-25-at-12.27.21" width="600" height="400" loading="lazy"></p>
<p>You can use the <code>match()</code> method to extract the numbers in JavaScript too:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> testStr =
  <span class="hljs-string">'Arabic numerals are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. From those ten numbers, you can write any number you want, including nonillion and decillion.'</span>;

<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/\d/g</span>;

<span class="hljs-built_in">console</span>.log(testStr.match(re));

<span class="hljs-comment">/* output
[
  '0', '1', '2', '3',
  '4', '5', '6', '7',
  '8', '9'
]
*/</span>
</code></pre>
<p>A more straightforward example is matching dates since dates are mostly in numbers. For example, if you want to match a date in the format <code>dd/mm/yyyy</code>, you can match it with the pattern <code>/\d\d\/\d\d\/\d\d\d\d/</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> date = <span class="hljs-string">'22/04/2023'</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/\d\d\/\d\d\/\d\d\d\d/</span>;

<span class="hljs-built_in">console</span>.log(re.test(date)); <span class="hljs-comment">// true</span>
</code></pre>
<p>Since you can also have a period or hyphen as the separator of a date, you can account for those too by putting all the possible separators in a character set:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> slashSeparatedSate = <span class="hljs-string">'22/04/2023'</span>;
<span class="hljs-keyword">const</span> hyphenSeparatedDate = <span class="hljs-string">'22-04-2023'</span>;
<span class="hljs-keyword">const</span> periodSeparatedDate = <span class="hljs-string">'22.04.2023'</span>;

<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/\d\d[/.-]\d\d[/.-]\d\d\d\d/</span>;

<span class="hljs-built_in">console</span>.log(re.test(slashSeparatedSate)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(re.test(hyphenSeparatedDate)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(re.test(periodSeparatedDate)); <span class="hljs-comment">// true</span>
</code></pre>
<p><strong>N.B.</strong>: The pattern above matches a date but also an invalid date like <code>99/45/2022</code>. A better way to match dates is provided in the applications of the regex chapter.</p>
<p>Another example is matching phone numbers. For example, US phone numbers are in the format <code>(123) 456-7890</code>. You can use the pattern <code>/\(\d\d\d\) \d\d\d-\d\d\d\d/</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> USPhone = <span class="hljs-string">'(123) 456-7890'</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/\(\d\d\d\) \d\d\d-\d\d\d\d/</span>;

<span class="hljs-built_in">console</span>.log(re.test(USPhone)); <span class="hljs-comment">// true</span>
</code></pre>
<p>The non-digit metacharacter is the opposite of the digit metacharacter. It matches all non-digit characters. That is, alphabets, spaces, and symbols. In other words, it is the shorthand character class for <code>[^0-9]</code>.</p>
<p>If you want to extract all non-digit characters in a string, you can use the <code>\D</code> metacharacter:
<img src="https://www.freecodecamp.org/news/content/images/2023/07/D-matches.png" alt="D-matches" width="600" height="400" loading="lazy"></p>
<p>This is it in JavaScript code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> testStr =
  <span class="hljs-string">'Arabic numerals are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. From those ten numbers, you can write any number you want, including nonillion and decillion.'</span>;

<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/\D/g</span>;

<span class="hljs-built_in">console</span>.log(testStr.match(re));

<span class="hljs-comment">/* output
A total of 137 matches is too much to show here, but you can test it out yourself.
*/</span>
</code></pre>
<h3 id="heading-the-square-brackets-metacharacter">The Square Brackets Metacharacter</h3>
<p>You've already seen the square brackets (<code>[]</code>) metacharacter in action. Square brackets are used for specifying a character class, or character set. And if you want to match them as a literal character, then you have to escape them.</p>
<p>One thing to have in mind is that some metacharacters lose their meanings inside the character set. The exceptions to this are:</p>
<ul>
<li>The caret (<code>^</code>) which you can use to negate a character set</li>
<li>The hyphen (<code>-</code>) which you can use to specify ranges</li>
</ul>
<p><strong>N.B.</strong>: Sometimes, you might encounter a situation where you have to escape some metacharacters inside a character set.</p>
<p>If you want to match any of those characters in a character set, you have to escape it. If you are just passing the three of those characters in directly, you don't need to escape them if the caret is not the first character.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> testStr =
  <span class="hljs-string">'If you want to match the caret (^), hyphen and (-) symbols in a character set, you might not have to escape them.'</span>;

<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/[-^]/g</span>;

<span class="hljs-built_in">console</span>.log(testStr.match(re)); <span class="hljs-comment">// [ '^', '-' ]</span>
</code></pre>
<p>But if the caret is the first character in the character set alongside some word and non-word character, you should escape it, otherwise it will negate all other characters:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/unescaped-caret.png" alt="unescaped-caret" width="600" height="400" loading="lazy"></p>
<h3 id="heading-the-word-boundary-and-non-word-boundary-metacharacters">The Word Boundary and Non-word Boundary Metacharacters</h3>
<p>The word boundary metacharacter is represented by <code>\b</code> and the non-word boundary metacharacter is represented by <code>\B</code>. Both let you match a specific part of a string where a word character and a non-word character exist.</p>
<p>Word boundary (<code>\b</code>) matches a position between a word character (<code>\w</code>) and a non-word character (<code>\W</code>), and vice versa. It can be useful when you want to match a certain word in a string, or if you want to make sure a particular word or character is in a string.</p>
<p>Here's an example in a regex tester:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/b-match.png" alt="b-match" width="600" height="400" loading="lazy"></p>
<p>And the same example in JavaScript code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr =
  <span class="hljs-string">'A Tiger can do everything a lion does, apart from being a family man.'</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/\blion\b/</span>;

<span class="hljs-built_in">console</span>.log(myStr.match(re));

<span class="hljs-comment">/*
Output:
[
  'lion',
  index: 28,
  input: 'A Tiger can do everything a lion does, apart from being a family man.',
  groups: undefined
]
*/</span>
</code></pre>
<p>If you use a <code>g</code> flag with the pattern and use the <code>match()</code> method, all the matches will be returned – as expected:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr =
  <span class="hljs-string">'A Tiger can do everything a lion does, apart from being a family man. Not even a tiger can intimidate a lion within his family.'</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/\blion\b/g</span>;

<span class="hljs-built_in">console</span>.log(myStr.match(re)); <span class="hljs-comment">// [ 'lion', 'lion' ]</span>
</code></pre>
<p>On the other hand, the non-word boundary (<code>\B</code>) is the opposite of the word boundary (<code>\b</code>). So, it matches everywhere a word boundary won't return a match. For example, "thin" in "everything":</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/thing-everything.png" alt="thing-everything" width="600" height="400" loading="lazy"></p>
<p>And also "code" in "freeCodeCamp" when you use the case insensitive (<code>i</code>) flag:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/code-freeCodeCamp.png" alt="code-freeCodeCamp" width="600" height="400" loading="lazy"></p>
<p>You can see that the first "code" in the text wasn't the match returned. That's the power of word and non-word boundary metacharacters.</p>
<p>Here's what the two reveal in JavaScript code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr1 =
  <span class="hljs-string">'A Tiger can do everything a lion does, apart from being a family man.'</span>;
<span class="hljs-keyword">const</span> myStr2 = <span class="hljs-string">'Learn to code for free on freeCodeCamp.'</span>;

<span class="hljs-keyword">const</span> re1 = <span class="hljs-regexp">/\Bthin\B/</span>;
<span class="hljs-keyword">const</span> re2 = <span class="hljs-regexp">/\Bcode\B/i</span>;

<span class="hljs-built_in">console</span>.log(myStr1.match(re1));
<span class="hljs-built_in">console</span>.log(myStr2.match(re2));

<span class="hljs-comment">/*
Output:
[
  'thin',
  index: 20,
  input: 'A Tiger can do everything a lion does, apart from being a family man.',
  groups: undefined
]
[
  'Code',
  index: 30,
  input: 'Learn to code for free on freeCodeCamp.',
  groups: undefined
]
*/</span>
</code></pre>
<h3 id="heading-the-parenthesis-metacharacter">The Parenthesis Metacharacter</h3>
<p>The parenthesis metacharacters (<code>(</code> and <code>)</code>) let you create grouping and capturing. With them, you can treat any group of characters as a single unit and apply a common modifier or quantifier to them. </p>
<p>Parenthesis is also used for creating both lookahead and lookbehind assertions.</p>
<p>When you create the group and assertions, you can reference them later in the same pattern with a backslash and the order in which they appear. For example, you can reference the first group by specifying <code>\1</code> in the pattern.</p>
<p>In this book, a whole chapter is dedicated to grouping and capturing. There, you will learn more about grouping and capturing so you can see the parenthesis metacharacters in action.</p>
<h3 id="heading-the-space-and-non-space-metacharacters">The Space and Non-space Metacharacters</h3>
<p>It is impossible for text to make sense without spaces. Not just a "space", but also other space characters like tabs, carriage returns, and new lines. This is why the space and non-space metacharacters are made available in regular expressions.</p>
<p>The space metacharacter is represented by <code>\s</code> and the non-space metacharacter is represented by <code>\S</code>.</p>
<p><code>\s</code> matches all space characters:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/s-match.png" alt="s-match" width="600" height="400" loading="lazy"></p>
<p>And <code>\S</code> matches all non-space metacharacters:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/S-matches.png" alt="S-matches" width="600" height="400" loading="lazy"></p>
<p>Here's how both the <code>\s</code> and <code>\S</code> metacharacters work in JavaScript code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr = <span class="hljs-string">'Learn to code for free on freeCodeCamp'</span>;
<span class="hljs-keyword">const</span> spaceRe = <span class="hljs-regexp">/\s/g</span>;
<span class="hljs-keyword">const</span> nonSpaceRe = <span class="hljs-regexp">/\S/g</span>;

<span class="hljs-built_in">console</span>.log(myStr.match(spaceRe)); <span class="hljs-comment">// [' ', ' ', ' ', ' ', ' ', ' '];</span>

<span class="hljs-built_in">console</span>.log(myStr.match(nonSpaceRe)); 
<span class="hljs-comment">// [</span>
<span class="hljs-comment">// 'L', 'e', 'a', 'r', 'n', 't',</span>
<span class="hljs-comment">// 'o', 'c', 'o', 'd', 'e', 'f',</span>
<span class="hljs-comment">// 'o', 'r', 'f', 'r', 'e', 'e',</span>
<span class="hljs-comment">// 'o', 'n', 'f', 'r', 'e', 'e',</span>
<span class="hljs-comment">// 'C', 'o', 'd', 'e', 'C', 'a',</span>
<span class="hljs-comment">// 'm', 'p'</span>
<span class="hljs-comment">// ]</span>
</code></pre>
<p>One cool thing you can do with <code>\s</code> in JavaScript is to replace all spaces with say, a hyphen, or any other thing you want:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr = <span class="hljs-string">'Learn to code for free on freeCodeCamp'</span>;
<span class="hljs-keyword">const</span> replaceHyphen = myStr.replace(spaceRe, <span class="hljs-string">'-'</span>);

<span class="hljs-built_in">console</span>.log(replaceHyphen); <span class="hljs-comment">// Learn-to-code-for-free-on-freeCodeCamp</span>
</code></pre>
<p>The space metacharacter does not just match the spacebar you press on the keyboard of your device. It also matches:</p>
<ul>
<li>A tab character</li>
<li>A carriage return character</li>
<li>A new line character</li>
<li>A vertical tab character</li>
<li>And a form feed character</li>
</ul>
<p>Here's an example:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/s-match-all.png" alt="s-match-all" width="600" height="400" loading="lazy"></p>
<p>You can't see the match for the carriage return but it's there:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/s-match-all-view-1.png" alt="s-match-all-view-1" width="600" height="400" loading="lazy"></p>
<p>If you want to match each of those space characters, they also have their unique metacharacters:</p>
<ul>
<li><code>\t</code> for tab</li>
<li><code>\r</code> for carriage return</li>
<li><code>\n</code> for new line</li>
<li><code>\v</code> for vertical tab</li>
<li><code>\f</code> for form feed.</li>
</ul>
<p>You should be aware that most of the time, <code>\s</code> is all you need because it can do the matching for any space character.</p>
<h3 id="heading-the-pipe-metacharacter">The Pipe Metacharacter</h3>
<p>Also known as the <code>OR</code> operator, the pipe metacharacter is represented by the pipe symbol (<code>|</code>). It lets you specify multiple alternatives for matching. </p>
<p>The pipe matches the character preceding it, or the character that follows it. For example, if you have <code>website|web\sapp</code> as your pattern, then one or both of <code>website</code> and <code>web app</code> will be returned as the match:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/web-webapp-alt.png" alt="web-webapp-alt" width="600" height="400" loading="lazy"></p>
<p>The evaluation goes from left to right. If a match is found on the left, it returns the match. And if there's no match on the left, the character on the right-hand side is evaluated for a possible match. If both characters on the left and right are in the test string, then both are returned as matches.</p>
<p>You can also have more than two characters separated by the pipe symbols. For instance, the pattern <code>/o|a|i|re/</code> would match <code>o</code>, <code>a</code>, <code>i</code>, and <code>re</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/a-o-i-alt-match.png" alt="a-o-i-alt-match" width="600" height="400" loading="lazy"></p>
<p>There's no limit to the characters you can separate with it.</p>
<p>You can see I used the <code>g</code> flag in those examples. If you don’t use the <code>g</code> flag and both the left and right characters are matches, only the first match in the test string will be returned:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/first-occur-i-o-a.png" alt="first-occur-i-o-a" width="600" height="400" loading="lazy"></p>
<p>Here's a clearer example:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/clearer-alt.png" alt="clearer-alt" width="600" height="400" loading="lazy"></p>
<p>Here's how using the <code>OR</code> operator works with the <code>g</code> flag in code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr = <span class="hljs-string">'The website and web app are running fine'</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/website|web\sapp/g</span>;

<span class="hljs-built_in">console</span>.log(myStr.match(re)); <span class="hljs-comment">// returns [ 'website', 'web app' ] because of the g flag</span>
</code></pre>
<p>And here's how it works without the <code>g</code> flag:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr = <span class="hljs-string">'The website and web app are running fine'</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/website|web\sapp/</span>;

<span class="hljs-keyword">const</span> matches = myStr.match(re);

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> match <span class="hljs-keyword">of</span> matches) {
  <span class="hljs-built_in">console</span>.log(match); <span class="hljs-comment">// returns "website" and ignores web app because there's no g flag</span>
}
</code></pre>
<h3 id="heading-how-to-match-repeated-characters-with-quantifiers">How to Match Repeated Characters With Quantifiers</h3>
<p>Repeated characters occur when the same character exists in multiple numbers consecutively.</p>
<p>When you have a repeated character in your test string, you don't need to repeat a particular character in your pattern to match it. That's because there are metacharacters available for <strong>one or more matches</strong>, <strong>zero or more matches</strong>, and <strong>zero or one matches</strong>, AKA <strong>optional matches</strong>.</p>
<h4 id="heading-one-or-more-matches-with-the-addition-sign-metacharacter">One or More Matches with the Addition Sign Metacharacter</h4>
<p>As you can guess, the addition sign metacharacter is represented with a plus (<code>+</code>). You can also call it the "one or more quantifier".</p>
<p>If you want a particular character to be repeated one or many times, that's what the addition sign metacharacter does. </p>
<p>For example, the pattern, <code>/fe+d/</code> will match any word with one letter <code>e</code> or multiple letters <code>e</code> that occur consecutively. For instance, <code>fed</code> and <code>feed</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/one-or-more-e.png" alt="one-or-more-e" width="600" height="400" loading="lazy"></p>
<p>A practical example in JavaScript is extracting vowels in a test string while limiting occurrences by making sure multiple vowels that follow one another are also returned:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr = <span class="hljs-string">'You should plant trees to save mother earth'</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/[aeiou]+/gi</span>;

<span class="hljs-built_in">console</span>.log(myStr.match(re));

<span class="hljs-comment">/*
Output:
[
  'ou', 'ou', 'a',
  'ee', 'o',  'a',
  'e',  'o',  'e',
  'ea'
]
*/</span>
</code></pre>
<p>You can also append the addition sign metacharacter to other metacharacters. For example, /\d+/ would match one or more digits:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/d--matches.png" alt="d--matches" width="600" height="400" loading="lazy"></p>
<p>You can also add the <code>+</code> metacharacter to a character set to repeat it one or more times. In the screenshot below, the pattern <code>/f[a-z]+/</code> would match one or more letter <code>f</code> followed by any set of small letters:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/f-set-zero-or-more.png" alt="f-set-zero-or-more" width="600" height="400" loading="lazy"></p>
<h4 id="heading-zero-or-more-matches-with-the-asterisk-metacharacter">Zero or More Matches with the Asterisk Metacharacter</h4>
<p>The asterisk metacharacter (<code>*</code>) matches zero or many occurrences of the character it comes after. You can also call it a "zero or more quantifier". </p>
<p>So, if you want a character to be repeated zero or more than one time, you can use the asterisk metacharacter. A basic example is using the pattern <code>/go*d/</code> would match any word that starts with the letter <code>g</code> followed by any number of the letter <code>o</code>, and ending with the letter <code>d</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/gd-zero-or-more.png" alt="gd-zero-or-more" width="600" height="400" loading="lazy"></p>
<p>Just like you can do with the plus metacharacter, you can also append the asterisk metacharacter to any other metacharacter. For example, you can match empty strings with the pattern <code>/\s*/</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/match-empty-string.png" alt="match-empty-string" width="600" height="400" loading="lazy"></p>
<p>Doubting that? Here it is in JavaScript code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/\s*/</span>;
<span class="hljs-keyword">const</span> emptyString = <span class="hljs-string">''</span>;

<span class="hljs-built_in">console</span>.log(re.test(emptyString)); <span class="hljs-comment">// true</span>
</code></pre>
<p>I didn’t know matching empty strings was as straightforward as this until I got to this point in the book!</p>
<p>Again, like the plus metacharacter, you can also add the <code>*</code> metacharacter to a character set to repeat it zero or more times:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/f-set-one-or-more.png" alt="f-set-one-or-more" width="600" height="400" loading="lazy"></p>
<p>Here's the same thing in JavaScript code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr = <span class="hljs-string">'You can make yourself free from diseases'</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/f[a-z]*/g</span>;

<span class="hljs-built_in">console</span>.log(myStr.match(re)); <span class="hljs-comment">// [ 'f', 'free', 'from' ]</span>
</code></pre>
<p>You can see the <code>f</code> in the word <code>yourself</code> is even a match too. That's one way to deduce that the asterisk (<code>*</code>) returns more matches than the addition sign (<code>+</code>) metacharacter because it is greedier. You will learn about greediness of a regular expression in the closing part of this chapter.</p>
<h4 id="heading-zero-or-one-matches-with-the-question-mark-metacharacter">Zero or One Matches with the Question Mark Metacharacter</h4>
<p>The question mark metacharacter (<code>?</code>) is also known as the zero or one quantifier. It lets you make the character that precedes it optional, so it plays an important role in preventing greediness.</p>
<p>For example, the pattern <code>/ab?c/</code> will match <code>abc</code> and <code>ac</code>, but never <code>abbbc</code> or any other numbers of <code>b</code> between the <code>a</code> and <code>c</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/abc-optional.png" alt="abc-optional" width="600" height="400" loading="lazy"></p>
<p>This is not the case with the other two metacharacters for matching repeated characters (<code>+</code> and <code>*</code>). The pattern <code>/ab*c/</code> will match all of  <code>abc</code>, <code>ac</code>, <code>abbbc</code>, and <code>abbbbbbbc</code> while <code>/ab+c/</code> will leave out <code>ac</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr = <span class="hljs-string">'abc ac abbbc abbbbbbbc'</span>;
<span class="hljs-keyword">const</span> re1 = <span class="hljs-regexp">/ab*c/g</span>;
<span class="hljs-keyword">const</span> re2 = <span class="hljs-regexp">/ab+c/g</span>;
<span class="hljs-keyword">const</span> re3 = <span class="hljs-regexp">/ab?c/g</span>;

<span class="hljs-built_in">console</span>.log(myStr.match(re1)); <span class="hljs-comment">// [ 'abc', 'ac', 'abbbc', 'abbbbbbbc' ]</span>
<span class="hljs-built_in">console</span>.log(myStr.match(re2)); <span class="hljs-comment">// [ 'abc', 'abbbc', 'abbbbbbbc' ]</span>
<span class="hljs-built_in">console</span>.log(myStr.match(re3)); <span class="hljs-comment">// [ 'abc', 'ac' ]</span>
</code></pre>
<p>A better example is tailoring a regex pattern to match words that have different spellings due to the small variations in British and American English. For example, <code>color</code> and <code>colour</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/colou-r-optional.png" alt="colou-r-optional" width="600" height="400" loading="lazy"></p>
<p>There's also <code>centre</code> and <code>center</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/cente-re--optional.png" alt="cente-re--optional" width="600" height="400" loading="lazy"></p>
<p>You can extract those words in JavaScript. You can't use the <code>match()</code> method for that because it causes some unexpected behaviors when used with the <code>?</code> metacharacter.</p>
<p>Here's how I was able to do it for <code>color</code> and <code>colour</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr = <span class="hljs-string">'The words center and centre are homophones'</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/cente?re?/g</span>;

<span class="hljs-keyword">let</span> match;
<span class="hljs-keyword">const</span> matches = [];

<span class="hljs-keyword">while</span> ((match = re.exec(myStr)) !== <span class="hljs-literal">null</span>) {
  matches.push(match[<span class="hljs-number">0</span>]);
}

<span class="hljs-built_in">console</span>.log(matches); <span class="hljs-comment">// ["center", "centre"]</span>
</code></pre>
<p>I used the same approach to extract <code>center</code> and <code>centre</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr =
  <span class="hljs-string">'It is "colour" in British English and "color" in American English'</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/colou?r/g</span>;

<span class="hljs-keyword">let</span> match;
<span class="hljs-keyword">const</span> matches = [];

<span class="hljs-keyword">while</span> ((match = re.exec(myStr)) !== <span class="hljs-literal">null</span>) {
  matches.push(match[<span class="hljs-number">0</span>]);
}

<span class="hljs-built_in">console</span>.log(matches); <span class="hljs-comment">// [ 'colour', 'color' ]</span>
</code></pre>
<p>Many times, it's challenging knowing which to use for character repetition between these three metacharacters – <code>*</code>, <code>+</code>, and <code>?</code>. It can even be hard to get used to what each of them does if you're just starting out with regular expressions.</p>
<p>Be aware that identifying them and knowing which to use between them is not a herculean task. Here are some things to note about the three of them:</p>
<ul>
<li>Asterisk (<code>*</code>) means "zero or many": use it if you want a character not to appear in the target string or you want the same character to be more than one</li>
<li>Plus (<code>+</code>) means "one or many": use it if you want a character to appear once or more than once in the target string</li>
<li>Question mark (<code>?</code>) means "zero or one": use it if you want a character to be optional in the target string.</li>
</ul>
<h3 id="heading-how-to-specify-match-quantity-with-the-curly-braces-metacharacter">How to Specify Match Quantity with the Curly Braces Metacharacter</h3>
<p>Quantifiers let you indicate the quantity or frequency of a preceding character in a pattern with curly braces (<code>{}</code>}. With those braces, you can specify an exact quantifier, a minimum quantifier, and a range quantifier.</p>
<h4 id="heading-the-range-quantifier">The Range Quantifier</h4>
<p>The general syntax for the range quantifier looks like this:</p>
<pre><code class="lang-console">char{n1,n2}
</code></pre>
<ul>
<li><code>cha</code> is any character you're applying the quantifier to</li>
<li><code>n1</code> is the minimum number of times you want the character to repeat</li>
<li><code>n2</code> is the maximum number of times you want the character to repeat</li>
</ul>
<p>An example is the pattern <code>/a{3,6}/</code>. This means you want to match between three and six letters <code>a</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/a-3-6--match.png" alt="a-3-6--match" width="600" height="400" loading="lazy"></p>
<p>If you have more than six letters <code>a</code> in the test string, the first six will match:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/a-range-error.png" alt="a-range-error" width="600" height="400" loading="lazy"></p>
<p>To fix this, you can surround the pattern in a word boundary:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/a-range-error-fix.png" alt="a-range-error-fix" width="600" height="400" loading="lazy"></p>
<p>You can also attach the range quantifier to metacharacters. For example, you can extract any number that is at least in hundreds this way:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr =
  <span class="hljs-string">'The marathon had 500 participants, with 251 finishing under 3 hours, and the winner crossed the line at 4800 seconds.'</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/\b\d{3,6}\b/g</span>;

<span class="hljs-built_in">console</span>.log(myStr.match(re)); <span class="hljs-comment">// [ '500', '251', '4800' ]</span>
</code></pre>
<h4 id="heading-the-minimum-quantifier">The Minimum Quantifier</h4>
<p>The minimum quantifier lets you specify the minimum number of times you want the character that precedes it to match. You can do this by putting a comma right after the number in the curly brace. The general syntax looks like this: <code>{n,}</code>. </p>
<p>For example, the pattern <code>/a{3,}/</code> means you want a minimum of three letters <code>a</code>. In this case, one letter <code>a</code> and two letters <code>a</code> won't be a match, but three letters <code>a</code> and upward would be returned as matches:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/a-3---match.png" alt="a-3---match" width="600" height="400" loading="lazy"></p>
<p>Let's extract those matches with the <code>match()</code> method:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr =
  <span class="hljs-string">'"a" won\'t match here. "aa" won\'t match too, but "aaa" is a match, "aaaa" is also a match, and every other number of "a"'</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/a{3,}/g</span>;

<span class="hljs-built_in">console</span>.log(myStr.match(re)); <span class="hljs-comment">// [ 'aaa', 'aaaa' ]</span>
</code></pre>
<h4 id="heading-the-exact-quantifier">The Exact Quantifier</h4>
<p>The exact specifier is represented by <code>{n}</code>. In this case, <code>n</code> stands for the exact number of times you want that character to be repeated. For instance, the pattern, <code>/a{3}/</code> means you want <code>a</code> to be repeated three times</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/exact-a-3-.png" alt="exact-a-3-" width="600" height="400" loading="lazy"></p>
<p>Unfortunately, a match is returned anywhere there are three letters <code>a</code> that follow one another. You can prevent this behavior with word boundary (<code>\b</code>):</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/exact-a-3--fixed-.png" alt="exact-a-3--fixed-" width="600" height="400" loading="lazy"></p>
<p>That way, you can extract the abbreviations, <code>AAA</code> from a string using the <code>match()</code> method. Below is an example: </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr =
  <span class="hljs-string">"There is American automobile association (AAA)and there is Australian automobile association (AAA). What I've never seen is AAAA or AAAAAA."</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/\ba{3}\b/gi</span>;

<span class="hljs-built_in">console</span>.log(myStr.match(re)); <span class="hljs-comment">// [ 'AAA', 'AAA' ]</span>
</code></pre>
<p>Remember the pattern I wrote to match dates in the <code>dd/mm/yyyy</code> format? You can make it better and easier to read with the exact quantifier like this:</p>
<pre><code class="lang-console">\d{2}[/.-]\d{2}[/.-]\d{4}
</code></pre>
<p>Everything still works fine:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> slashSeparatedSate = <span class="hljs-string">'22/04/2023'</span>;
<span class="hljs-keyword">const</span> hyphenSeparatedDate = <span class="hljs-string">'22-04-2023'</span>;
<span class="hljs-keyword">const</span> periodSeparatedDate = <span class="hljs-string">'22.04.2023'</span>;

<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/\d{2}[/.-]\d{2}[/.-]\d{4}/</span>;

<span class="hljs-built_in">console</span>.log(re.test(slashSeparatedSate)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(re.test(hyphenSeparatedDate)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(re.test(periodSeparatedDate)); <span class="hljs-comment">// true</span>
</code></pre>
<p>You can also make the pattern that matches the US phone number better and shorter with the same approach:</p>
<pre><code class="lang-console">\(\d{3}\) \d{3}-\d{4}
</code></pre>
<p>Everything still works fine too:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> USPhone = <span class="hljs-string">'(123) 456-7890'</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/\(\d{3}\) \d{3}-\d{4}/</span>;

<span class="hljs-built_in">console</span>.log(re.test(USPhone)); <span class="hljs-comment">// true</span>
</code></pre>
<h3 id="heading-the-wildcard-metacharacter">The Wildcard Metacharacter</h3>
<p>The wildcard metacharacter is represented by a dot (<code>.</code>), so you can also call it the dot metacharacter. </p>
<p>The wildcard lets you match any character apart from a new line (<code>\n</code>). That means you can use it to match alphanumeric characters, spaces, and symbols.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/wcard-match.png" alt="wcard-match" width="600" height="400" loading="lazy"></p>
<p>You can also attach the wildcard metacharacter to another metacharacter. For example, the pattern <code>/\d./g</code> should match at least a number and everything that follows it:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/digit-greedy.png" alt="digit-greedy" width="600" height="400" loading="lazy"></p>
<p>You can see that the pattern is transcending beyond the digits by matching the spaces after them. This is what is called <strong>greediness</strong>.</p>
<p>The pattern, <code>/\d.*/g</code> is even more greedy because it will match everything after it encounters the first number:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/super-digit-greedy.png" alt="super-digit-greedy" width="600" height="400" loading="lazy"></p>
<p>It’s the same in code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr =
  <span class="hljs-string">'An example of a two-digit number is 20. 100 is a three-digit number. 300 and 900 are also three-digit numbers.'</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/\d.*/g</span>;

<span class="hljs-built_in">console</span>.log(myStr.match(re)); <span class="hljs-comment">// [ '20. 100 is a three-digit number. 300 and 900 are also three-digit numbers.']</span>
</code></pre>
<p>If you want the wildcard to match a new line too, you can use the <code>s</code> flag. Here's an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> codeBlock = <span class="hljs-string">`
  function add(x, y) {
    /* This is a function
    that takes two numbers
    and adds them together. */
    return x + y;
  }
`</span>;

<span class="hljs-keyword">let</span> commentRegex = <span class="hljs-regexp">/\/\*(.*)\*\//</span>s; <span class="hljs-comment">// gets everything between /* and */</span>

<span class="hljs-keyword">const</span> match = codeBlock.match(commentRegex);
<span class="hljs-built_in">console</span>.log(match);
</code></pre>
<p>Here's the result:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/dotAllRes-1.png" alt="dotAllRes-1" width="600" height="400" loading="lazy"></p>
<p>You can use the <code>dotAll</code> property to check if the <code>s</code> flag is used in the pattern:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> codeBlock = <span class="hljs-string">`
  function add(x, y) {
    /* This is a function
    that takes two numbers
    and adds them together. */
    return x + y;
  }
`</span>;

<span class="hljs-keyword">let</span> commentRegex = <span class="hljs-regexp">/\/\*(.*)\*\//</span>s; <span class="hljs-comment">// gets everything between /* and */</span>
<span class="hljs-keyword">const</span> match = codeBlock.match(commentRegex);

<span class="hljs-built_in">console</span>.log(commentRegex.dotAll) <span class="hljs-comment">// true;</span>
</code></pre>
<p>You can extract the match with an if statement:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> codeBlock = <span class="hljs-string">`
  function add(x, y) {
    /* This is a function
    that takes two numbers
    and adds them together. */
    return x + y;
  }
`</span>;

<span class="hljs-keyword">let</span> commentRegex = <span class="hljs-regexp">/\/\*(.*)\*\//</span>s; <span class="hljs-comment">// gets everything between /* and */</span>

<span class="hljs-keyword">const</span> match = codeBlock.match(commentRegex);

<span class="hljs-keyword">if</span> (match) {
  <span class="hljs-built_in">console</span>.log(match[<span class="hljs-number">1</span>]);
}

<span class="hljs-comment">/*
Output:  
This is a function
    that takes two numbers
    and adds them together.
*/</span>
</code></pre>
<p>Because the wildcard always matches any character it encounters apart from a new line, it is better not to use it unless it is absolutely necessary. For every character the wildcard matches, there is always another way to match it.</p>
<h3 id="heading-greediness-and-laziness-in-regular-expressions">Greediness and Laziness in Regular Expressions</h3>
<p>By default, regular expression patterns are greedy, meaning they always try to match as many as possible characters. But the concept of greediness is primarily applicable to quantifiers (<code>*</code>, <code>+</code>, <code>?</code>, and <code>{}</code>) and the wildcard (<code>.</code>).</p>
<p>For Example, the pattern <code>/f.*h/gi</code> will match as many characters as possible after encountering an <code>f</code> in the target string:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/asterisk-greedy.png" alt="asterisk-greedy" width="600" height="400" loading="lazy"></p>
<p>Same for the pattern, <code>/f.*h/gi</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/plus-greedy.png" alt="plus-greedy" width="600" height="400" loading="lazy"></p>
<p>It’s the same in code: </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr = <span class="hljs-string">'The fresh fish was caught in the Finnish lake'</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/f.*h/gi</span>;

<span class="hljs-built_in">console</span>.log(myStr.match(re)); <span class="hljs-comment">// [ 'fresh fish was caught in the Finnish' ]</span>
</code></pre>
<p><strong>Laziness</strong> is the opposite of greediness and it’s the way you stop greediness. On many occasions, if you want to stop greediness, all you need is to apply the <strong>zero or ones quantifier</strong> (<code>?</code>) to the metacharacter causing the greediness.</p>
<p>Here's how I stopped the greediness of the asterisk metacharacter:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/make-asterisk-lazy.png" alt="make-asterisk-lazy" width="600" height="400" loading="lazy"></p>
<p>I stopped it for the plus metacharacter the same way:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/make-plus-lazy.png" alt="make-plus-lazy" width="600" height="400" loading="lazy"></p>
<p>I can now safely extract every word that starts with <code>f</code> and ends with <code>h</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr = <span class="hljs-string">'The fresh fish was caught in the Finnish lake'</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/f.*?h/gi</span>;

<span class="hljs-built_in">console</span>.log(myStr.match(re)); <span class="hljs-comment">// [ 'fresh', 'fish', 'Finnish' ]</span>
</code></pre>
<h2 id="heading-chapter-6-grouping-and-capturing-in-regex">Chapter 6: Grouping and Capturing in Regex</h2>
<h3 id="heading-what-is-grouping">What is Grouping?</h3>
<p>Grouping means treating a regex pattern or a part of a regex pattern as a single unit. To achieve grouping, you surround the pattern or the part of the pattern you want to group in parenthesis (<code>(</code> and <code>)</code>).</p>
<p>After you've grouped the part of the pattern you want to, you can then refer back to it through a process we call "backreferencing" in regular expressions.</p>
<p>The groups you define in a pattern refer to the target string or text and not the pattern itself. You'll see this in action when it's time to discuss backreferencing. </p>
<p>After grouping, you can then apply a quantifier to that group since all the patterns in it are a unit.</p>
<p>Let's say you have a group of the ids <code>z8g4g4 ga1v4g f4k7f9 bb3b2b d6b4t5 d4cm3d e9f5y6 ggj64 mgtyqg m0foh9</code> and you want to find out which of them follow the pattern <code>letter number letter number letter number</code>. The pattern <code>[a-z]\d[a-z]\d[a-z]\d</code> can do that for you:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/without-grouping.png" alt="without-grouping" width="600" height="400" loading="lazy"></p>
<p>Using grouping, you can make the pattern shorter by grouping the <code>[a-z]\d</code> sequence and applying an exact quantifier of <code>3</code> to it:</p>
<pre><code class="lang-console">([a-z]\d){3}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/with-grouping.png" alt="with-grouping" width="600" height="400" loading="lazy"></p>
<p>When you use grouping in a pattern, especially if you have multiple groups in the same pattern, you can use the <code>exec()</code> method to extract each of the groups.</p>
<p>A good example to illustrate this is a date in any acceptable format, for example <code>dd/mm/yyyy</code>.</p>
<p>Here's how I group the pattern <code>\d\d[/.-]\d\d[/.-]\d\d\d\d</code> into <code>dd</code>, <code>mm</code>, and <code>yyyy</code>:</p>
<pre><code class="lang-console">(\d\d)[/.-](\d\d)[/.-](\d\d\d\d)
</code></pre>
<p>I used the <code>exec()</code> method this way:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/(\d\d)[/.-](\d\d)[/.-](\d\d\d\d)/</span>;
<span class="hljs-keyword">const</span> date = <span class="hljs-string">'22-03-2023'</span>;

<span class="hljs-keyword">const</span> execRes = re.exec(date);
<span class="hljs-built_in">console</span>.log(execRes);
</code></pre>
<p>This is what the result looks like in the console:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/exec-group-res.png" alt="exec-group-res" width="600" height="400" loading="lazy"></p>
<p>In the array, you can see that:</p>
<ul>
<li>there is the whole date in the index <code>0</code></li>
<li>the index <code>1</code> has the <code>day</code></li>
<li>the index <code>2</code> has the month`</li>
<li>and the index <code>3</code> has the <code>year</code></li>
</ul>
<p>You can then use array referencing to get all of those figures:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/(\d\d)[/.-](\d\d)[/.-](\d\d\d\d)/</span>;
<span class="hljs-keyword">const</span> date = <span class="hljs-string">'22-03-2023'</span>;

<span class="hljs-keyword">const</span> execRes = re.exec(date);

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The full date is <span class="hljs-subst">${execRes[<span class="hljs-number">0</span>]}</span>`</span>); <span class="hljs-comment">// The full date is 22-03-2023</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The day is <span class="hljs-subst">${execRes[<span class="hljs-number">1</span>]}</span>`</span>); <span class="hljs-comment">// The day is 22</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The month is <span class="hljs-subst">${execRes[<span class="hljs-number">2</span>]}</span>`</span>); <span class="hljs-comment">// The month is 03</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The year is <span class="hljs-subst">${execRes[<span class="hljs-number">3</span>]}</span>`</span>); <span class="hljs-comment">// The year is 2023</span>
</code></pre>
<p>You can also use this approach to extract a username and domain from an email:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">extractUsernameAndDomain</span>(<span class="hljs-params">email</span>) </span>{
  <span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/([a-z]{2,})@([a-z]{3,}\.com)/</span>;
  <span class="hljs-keyword">const</span> result = re.exec(email);

  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The username is <span class="hljs-subst">${result[<span class="hljs-number">1</span>]}</span>`</span>);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The domain is <span class="hljs-subst">${result[<span class="hljs-number">2</span>]}</span>`</span>);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The full email is <span class="hljs-subst">${result[<span class="hljs-number">0</span>]}</span>`</span>);
}

extractUsernameAndDomain(<span class="hljs-string">'janedoe@gmail.com'</span>);

<span class="hljs-comment">/*
Output:
The username is janedoe
The domain is gmail.com
The full email is janedoe@gmail.com
*/</span>
</code></pre>
<p>This behavior of grouping in which each match of the pattern is separated in an array according to the groups is the reason groups are also called "capturing" groups. This way, you don’t need the <code>split()</code> method of JavaScript or any other programming hacks to get each of the groups on those dates.</p>
<h3 id="heading-how-to-reference-captured-groups-with-backreferences">How to Reference Captured Groups with Backreferences</h3>
<p>Since groups are captured by default, you can refer back to them. To do this, you use a backslash (<code>\</code>) and then the order of the group in the pattern. For example, you can reference the first group with <code>\1</code> and the third group with <code>\3</code>. No zero indentation.</p>
<p>Let's say you want to match "tsetse" fly in the text <code>There are many tsetse flies in the tropics</code>. If you group the text "tse" first and use the <code>g</code> flag, you'll get two matches:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/tse-group-warn.png" alt="tse-group-warn" width="600" height="400" loading="lazy"></p>
<p>You can refer back to that <code>tse</code> group with <code>\1</code> and you'll have a single match: </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/tse-group-right.png" alt="tse-group-right" width="600" height="400" loading="lazy"></p>
<p>It's very important to note that when you use a capturing group, the grouping refers to the target string (or text) and not the pattern itself. The reason why the pattern <code>/(tse)\1/</code> returns a match in the last example is because of the "tse" in the text and not the "tse" in the pattern.</p>
<p>To illustrate this, let's use a date again, since the month or date and the separators can repeat and can be different. I will use the pattern <code>(\d\d)([/.-])\1\2(\d\d\d\d)</code> for matching dates that I grouped in one of the previous examples. Remember the pattern successfully matches a date:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/date-match-group.png" alt="date-match-group" width="600" height="400" loading="lazy"></p>
<p>I can group the separator too and refer back to it for the second separator. I can also refer back to the day part of the date to match the month, since they both look for two digits. </p>
<p>Here's the new pattern now:</p>
<pre><code class="lang-console">(\d\d)([/.-])\1\2(\d\d\d\d)
</code></pre>
<p>I can make the pattern shorter with an exact quantifier:</p>
<pre><code class="lang-console">(\d{2})([/.-])\1\2(\d{4})
</code></pre>
<p>The new pattern successfully matches the same date:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/date-match-group-same.png" alt="date-match-group-same" width="600" height="400" loading="lazy"></p>
<p>But the reason there's a match in the example above is that the separators are the same and the day and month are the same.</p>
<p>If the day is different from the month, there won't be a match:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/no-match-because-of-day-month-difference.png" alt="no-match-because-of-day-month-difference" width="600" height="400" loading="lazy"></p>
<p>If the separators are different too, there also won't be a match:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/no-match-because-of-separator-difference.png" alt="no-match-because-of-separator-difference" width="600" height="400" loading="lazy"></p>
<p>But remember that if both are the same, there will be a match:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/date-match-group-same-1.png" alt="date-match-group-same-1" width="600" height="400" loading="lazy"></p>
<p>That is the reason why the groups in a pattern refer to the target string (or text) and not the pattern itself. </p>
<p>It is also possible to make a group non-capturing. That way, you won't be able to refer to it in the pattern. To create a <strong>non-capturing</strong> group, you use a question mark and a colon right after the opening parenthesis.</p>
<p>The syntax for that looks like this:</p>
<pre><code class="lang-console">(?: chars)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/no-match-non-capture.png" alt="no-match-non-capture" width="600" height="400" loading="lazy"></p>
<p>Because of this, the text does not match the pattern anymore. To make it match again I have to:</p>
<ul>
<li>remove the first backreference (<code>\1</code>)</li>
<li>define <code>\d{2}</code> for the date</li>
<li>change the reference to the separator from <code>\2</code> to <code>\1</code></li>
</ul>
<p>Here’s the new pattern:</p>
<pre><code class="lang-console">(?:\d{2})([/.-])\d{2}\1(\d{4})
</code></pre>
<p>And now the date matches the pattern:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/match-non-capture.png" alt="match-non-capture" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-use-the-d-flag-and-hasindices-property-with-groups">How to Use the <code>d</code> Flag and <code>hasIndices</code> Property with Groups</h3>
<p>The <code>d</code> flag adds index information to match objects for capture groups. This way, you won't just know what was matched by each capture group, but also where that match was found in the input string.</p>
<p>Let's look at how this works with the grouping for matching dates:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/(\d\d)[/.-](\d\d)[/.-](\d\d\d\d)/</span>d;
<span class="hljs-keyword">const</span> date = <span class="hljs-string">'22-03-2023'</span>;

<span class="hljs-keyword">const</span> match = re.exec(date);
<span class="hljs-built_in">console</span>.log(match);
</code></pre>
<p>The result contains an array of objects detailing the total position of all matches, and the position of each match:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/dFlagRes.png" alt="dFlagRes" width="600" height="400" loading="lazy"></p>
<p>If you want to see those indices, you can use <code>.indices</code> to see them:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/(\d\d)[/.-](\d\d)[/.-](\d\d\d\d)/</span>d;
<span class="hljs-keyword">const</span> date = <span class="hljs-string">'22-03-2023'</span>;

<span class="hljs-keyword">const</span> match = re.exec(date);

<span class="hljs-built_in">console</span>.log(match.indices);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/dFlagHasIndicesRes.png" alt="dFlagHasIndicesRes" width="600" height="400" loading="lazy"></p>
<p>You can also extract those indices separately:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/(\d\d)[/.-](\d\d)[/.-](\d\d\d\d)/</span>d;
<span class="hljs-keyword">const</span> date = <span class="hljs-string">'22-03-2023'</span>;

<span class="hljs-keyword">const</span> match = re.exec(date);

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The full index range is <span class="hljs-subst">${match.indices[<span class="hljs-number">0</span>]}</span>`</span>); <span class="hljs-comment">//The full index range is 0,10</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The day index range is <span class="hljs-subst">${match.indices[<span class="hljs-number">1</span>]}</span>`</span>); <span class="hljs-comment">// The day index range is 0,2</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The month index range is <span class="hljs-subst">${match.indices[<span class="hljs-number">2</span>]}</span>`</span>); <span class="hljs-comment">// The month index range is 3,5</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The year index range is <span class="hljs-subst">${match.indices[<span class="hljs-number">3</span>]}</span>`</span>); <span class="hljs-comment">// The year index range is 6,10</span>
</code></pre>
<p>And finally, you can check if the <code>d</code> flag is really used with the <code>hasIndices</code> property:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/(\d\d)[/.-](\d\d)[/.-](\d\d\d\d)/</span>d;
<span class="hljs-keyword">const</span> date = <span class="hljs-string">'22-03-2023'</span>;

<span class="hljs-built_in">console</span>.log(re.hasIndices); <span class="hljs-comment">// true</span>
</code></pre>
<h2 id="heading-chapter-7-lookaround-groups-lookaheads-and-lookbehinds">Chapter 7: Lookaround Groups: Lookaheads and Lookbehinds</h2>
<h3 id="heading-what-are-lookaround-groups">What are Lookaround Groups?</h3>
<p>Lookaround assertions are non-capturing groups that return matches only if the target string is followed or preceded by a particular character. </p>
<p>Lookaround assertions do not consume the characters in the input string or text. This makes them a "zero-width assertion", and that's why lookaround groups are also called "lookahead assertions".</p>
<p>There are two types of lookaround groups: <strong>lookahead</strong> and <strong>lookbehind</strong>. The two also have their positive and negative forms, so there are <strong>positive lookahead</strong>, <strong>negative lookahead</strong>, <strong>positive lookbehind</strong>, and <strong>negative lookbehind</strong> groups.</p>
<h3 id="heading-what-is-a-lookahead-group">What is a Lookahead Group?</h3>
<p>A lookahead group is a non-capturing group that lets you match a part of a string only if it is followed by another character in the string, without including that string or text to match in the pattern.</p>
<p>A lookahead group is useful when you want to match a string based on a condition. So, look at it like an <code>if</code> statement in a programming language.</p>
<p>There are two types of lookaheads, namely <strong>positive lookahead</strong> and <strong>negative lookahead</strong>.</p>
<p>Because you're still dealing with groupings, a positive lookahead is specified by an opening parenthesis followed by a question mark, an equal sign, the characters, and a closing parenthesis:</p>
<pre><code class="lang-console">(?=chars)
</code></pre>
<p>For example, the pattern <code>x(?=y)</code> means match <code>x</code> only if it is followed by <code>y</code>.</p>
<p>In the syntax of negative lookahead, you replace the equal sign with an exclamation mark:</p>
<pre><code class="lang-console">(?!chars)
</code></pre>
<p>For example, the pattern <code>x(?!y)</code> means do not match <code>x</code> if it is followed by <code>y</code>.</p>
<p>Let's look at an example of a positive lookahead assertion.</p>
<p>Say you want to match the domain name of domains that have only the <code>.org</code> extension within a string of domains with other extensions. This pattern would do it:</p>
<pre><code class="lang-console">[a-zA-Z]+(?=\.org)
</code></pre>
<p>In the pattern, <code>[a-zA-Z]+</code> represents one or more word characters, and <code>(?=\.org)</code> checks whether the domain contains a <code>.org</code> extension.</p>
<p>In the screenshot below, you can see that domain names that have a <code>.org</code> extension were matched:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/org-matches.png" alt="org-matches" width="600" height="400" loading="lazy"></p>
<p>You also can see that the words "freeCodeCamp" and "catholic" were not included in the pattern, but they still matched the pattern because they have the <code>.org</code> extension.</p>
<p>If there are no domains with the <code>.org</code> extension in the target string, there won't be any match. That's true for the domains without the <code>.org</code> extension.</p>
<p>That way, you can extract text like that in JavaScript and do whatever you want with it:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> domains = <span class="hljs-string">'koladechris.com freeCodeCamp.org mdn.com catholic.org'</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/[a-zA-Z]+(?=\.org)/g</span>;

<span class="hljs-keyword">const</span> charityWebsitesArr = domains.match(re);
<span class="hljs-keyword">const</span> charityWebsites = charityWebsitesArr.join(<span class="hljs-string">','</span>).replace(<span class="hljs-regexp">/,/</span>, <span class="hljs-string">' and '</span>);

<span class="hljs-built_in">console</span>.log(charityWebsites, <span class="hljs-string">'are examples of charity organizations.'</span>); <span class="hljs-comment">//freeCodeCamp and catholic are examples of charity organizations.</span>
</code></pre>
<p>If you want to match the <code>.org</code> as well so the whole domain gets matched, you have to include the <code>.org</code> in the pattern:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/org-all-match.png" alt="org-all-match" width="600" height="400" loading="lazy"></p>
<p>Since lookahead groups don’t consume characters, you will see a lot of developers use positive lookaheads to validate passwords.</p>
<p>Let's say you want the password to be at least six characters that includes a lowercase letter, an uppercase letter, a number, and a symbol. You can use lookaheads to define all of those conditions:</p>
<ul>
<li><code>(?=.{6,})</code> ¬– at least 6 characters</li>
<li><code>(?=.*[a-z])</code> – at least one lowercase character, but check if there are zero or many characters before it</li>
<li><code>(?=.*[A-Z])</code> – at least one lowercase character, but check if there are zero or many characters before it</li>
<li><code>(?=.*[0-9])</code> – at least one number, but check if there are zero or many characters before it</li>
<li><code>(?=.*[!@#$%%^&amp;*()+=-])</code> – accepted symbols, but check if there are zero or many characters before each</li>
<li><code>.*</code> – check if there are zero or many characters after the groups</li>
</ul>
<p>Here's the full regular expression:</p>
<pre><code class="lang-js">(?=.{<span class="hljs-number">6</span>,})(?=.*[a-z])(?=.*[A-Z])(?=.*[<span class="hljs-number">0</span><span class="hljs-number">-9</span>])(?=.*[!@#$%%^&amp;*()+=-]).*
</code></pre>
<p>And here is what matches the pattern and what does not:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/pword-lookahead.png" alt="pword-lookahead" width="600" height="400" loading="lazy"></p>
<p>To use that pattern in JavaScript, you can test it against a password string and do something from there:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> password = <span class="hljs-string">'Tse23*'</span>;
<span class="hljs-keyword">const</span> passwordRe =
  <span class="hljs-regexp">/(?=.{6,})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%%^&amp;*()+=-]).*/</span>;

<span class="hljs-keyword">if</span> (passwordRe.test(password)) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Welcome to your dashboard!'</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Incorrect password!'</span>);
}

<span class="hljs-comment">/**
output: Welcome to your dashboard!
*/</span>
</code></pre>
<p>For the application of negative lookahead, it is useful when you don't want a certain character before the character(s) you are looking for in a string. </p>
<p>Let's say you want to extract all items of an array that do not have the article "the" before them. In that case, you can use the pattern below:</p>
<pre><code class="lang-console">/^(?!.*\bThe\b).*$/
</code></pre>
<p>In the pattern above:</p>
<ul>
<li><code>^</code> ensures the regex pattern matches from the start of the line</li>
<li><code>(?!.*\bThe\b)</code> is the negative lookbehind that ensures that the article "the" is not in the target string</li>
<li><code>\bThe\b</code> is a word boundary that matches "The" and nothing else</li>
<li><code>.*</code> the wildcard that matches any character apart from a new line</li>
</ul>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> docTitles = [
  <span class="hljs-string">'The Incredible Dr. Poll'</span>,
  <span class="hljs-string">'Born in Africa'</span>,
  <span class="hljs-string">"America's Funniest Home Videos"</span>,
  <span class="hljs-string">'The Lion Queen'</span>,
  <span class="hljs-string">'Snake in the City'</span>,
];
<span class="hljs-keyword">let</span> re = <span class="hljs-regexp">/^(?!.*\bThe\b).*$/</span>;

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> title <span class="hljs-keyword">of</span> docTitles) {
  <span class="hljs-keyword">if</span> (re.test(title)) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`A Title without "The": <span class="hljs-subst">${title}</span>`</span>);
  }
}

<span class="hljs-comment">/*
Output:
A Title without "The": Born in Africa
A Title without "The": America's funniest home videos
A Title without "The": Snake in the City
*/</span>
</code></pre>
<h3 id="heading-what-is-a-lookbehind-group">What is a Lookbehind Group?</h3>
<p>A lookbehind group is similar to lookahead group. But instead of checking if a certain character(s) follows what you're trying to match, it checks whether the character(s) precedes what you're trying to match.</p>
<p>So, a lookbehind group is a non-capturing group that lets you match a part of a string only if it is preceded by another character in the string, without including that string or text to match in the pattern.</p>
<p>Like lookaheads, there are also positive and negative lookbehind assertions. A positive lookbehind returns a match only if the character you want to match is preceded by another character you specify in your pattern. On the other hand, a negative lookbehind returns a match only if the character you want to match is not preceded by another character.</p>
<p>A positive lookbehind is represented by an opening parenthesis, a question mark, a less than symbol, an equals sign, the character(s), and a closing parenthesis:</p>
<pre><code class="lang-console">(?&lt;=chars)
</code></pre>
<p>For example, the pattern <code>(?&lt;=x)y</code> indicates you want to match <code>y</code> only if there's <code>x</code> before it. In this case, <code>xx</code> or <code>yx</code> won't match, but <code>xy</code> would match.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/positive-lookbehind-match.png" alt="positive-lookbehind-match" width="600" height="400" loading="lazy"></p>
<p>For a negative lookbehind, an exclamation mark replaces the equals sign:</p>
<pre><code class="lang-console">(?&lt;!chars)
</code></pre>
<p>For example, the pattern <code>(?&lt;!x)y</code> means do not match <code>y</code> if there's <code>x</code> before it. In this case <code>by</code> would match, <code>my</code>, would match, but never <code>xy</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/negative-lkb-match.png" alt="negative-lkb-match" width="600" height="400" loading="lazy"></p>
<p>Positive lookbehind groups can be useful for matching numbers preceded only by a certain currency symbol, for example numbers preceded by the dollar sign.</p>
<p>The regex pattern below has a positive lookbehind that matches a number only if it is preceded by a dollar sign:</p>
<pre><code class="lang-js">(?&lt;=\$)\d+(\.\d*)?
</code></pre>
<p>In the pattern above, the lookbehind (<code>(?&lt;=\$)</code>) checks whether there's a dollar sign before one or more digits (represented by <code>\d+</code>). The other group, <code>(\.\d*)</code>, and the zero or one quantifier (<code>?</code>) check whether the number contains floating points.</p>
<p>Here's what matches and what does not:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/positive-lkb-match.png" alt="positive-lkb-match" width="600" height="400" loading="lazy"></p>
<p>In JavaScript, what you can do with the numbers that match is to calculate the total with the <code>reduce()</code> method:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myStr =
  <span class="hljs-string">'10 pieces of the items cost $102.99, but you can get 15 for a discount of $2, and 20 for a discount of $3.99'</span>;

<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/(?&lt;=\$)\d+(\.\d*)?/g</span>;

<span class="hljs-comment">// put all the prices in an array</span>
<span class="hljs-keyword">const</span> allPrices = myStr.match(re); <span class="hljs-comment">// [ '102.99', '2', '3.99' ]</span>

<span class="hljs-comment">// convert each of the prices to a number with map() and unary plus</span>
<span class="hljs-keyword">const</span> allPricesToNum = allPrices.map(<span class="hljs-function">(<span class="hljs-params">price</span>) =&gt;</span> +price); <span class="hljs-comment">// [ 102.99, 2, 3.99 ]</span>

<span class="hljs-comment">// add all the numbers with reduce()</span>
<span class="hljs-keyword">const</span> sumOfAllPrices = allPricesToNum.reduce(<span class="hljs-function">(<span class="hljs-params">acc, curr</span>) =&gt;</span> acc + curr, <span class="hljs-number">0</span>); <span class="hljs-comment">// 108.97999999999999</span>

<span class="hljs-comment">// add a dolar sign to the number and use toFixed() to round it down</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`$<span class="hljs-subst">${sumOfAllPrices.toFixed(<span class="hljs-number">2</span>)}</span>`</span>); <span class="hljs-comment">// $108.98</span>
</code></pre>
<p>For the example of negative lookbehind, let's say you want to match a digit as long as it is not preceded by the dollar sign. This pattern does it:</p>
<pre><code class="lang-js">(?&lt;!\$)\d+
</code></pre>
<p>But unfortunately, it still looks out for a number inside another number and matches it even if there's a dollar sign before the whole number:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/dollar-negative-lkb-err.png" alt="dollar-negative-lkb-err" width="600" height="400" loading="lazy"></p>
<p>To correct that behavior, you can surround the whole pattern with a word boundary (<code>\b</code>):</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/dollar-negative-lkb-fix.png" alt="dollar-negative-lkb-fix" width="600" height="400" loading="lazy"></p>
<p>Negative lookbehind groups are supported in JavaScript as well:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> monies = <span class="hljs-string">'$123 456 $789 £12 ₦568 $8903 £345'</span>;
<span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/\b(?&lt;!\$)\d+\b/g</span>;

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Monies without dollar sign:'</span>, monies.match(re)); <span class="hljs-comment">// Monies without dollar sign: [ '456', '12', '568', '345' ]</span>
</code></pre>
<h2 id="heading-chapter-8-regex-best-practices-and-troubleshooting">Chapter 8: Regex Best Practices and Troubleshooting</h2>
<h3 id="heading-best-practices-to-consider-while-writing-regular-expressions">Best Practices to Consider While Writing Regular Expressions</h3>
<p>Over time, regular expressions can become complex and hard to understand, depending on the use case and purpose. Things may become more complicated if it takes you a long time to come back to them or you work in a team.</p>
<p>Luckily, there are a few best practices to consider while writing regular expressions so you can make things easier for yourself and your team members.</p>
<p>Here are those best practices:</p>
<ul>
<li><p><strong>Keep it simple and readable</strong>: a simple, easy-to-read, and effective regex is better than a complex and effective regex. If you can make the regex efficient without using the complex concept of non-capturing groups like lookarounds (lookaheads and lookbehinds), then don’t use them.</p>
</li>
<li><p><strong>Avoid greedy matches</strong>: metacharacters like <code>*</code> and <code>+</code> and the wildcard (<code>.</code>) are greedy by default. It's hard to do without them, but when you use them and they cause greediness, make sure you use the zero or one quantifier (<code>?</code>) on them. In addition, avoid using the wildcard where necessary.</p>
</li>
<li><p><strong>Use comments to describe what a regex does</strong>: if you're working in a team, try to explain what the regexes you write do so others can understand them without wasting time.</p>
</li>
<li><p><strong>Use online regex testers</strong>: instead of writing your regular expressions in your code editor, write them in regex testers where you can test what they match without writing some more code. Free online regex testers like regex101 and regexpal.com also play a role in debugging because they can highlight errors and tell you what's wrong. </p>
</li>
<li><p><strong>Escape special characters</strong>: if you want to perform a literal match on metacharacters like <code>.</code>, <code>*</code>, <code>+</code>, <code>{</code>, <code>}</code>, and others, don’t forget to escape them unless you're using them inside a character set. Sometimes, you even have to escape hyphens in a character set. </p>
</li>
</ul>
<h3 id="heading-how-to-write-accurate-regular-expressions">How to Write Accurate Regular Expressions</h3>
<p>Writing accurate regular expressions with precision requires understanding what you want to match, the pattern to use, attention to detail, and an understanding of the underlying syntax and behavior of regular expressions in general.</p>
<p>This is crucial in order to ensure there are no avoidable errors and make sure the regexes you write effectively match the desired string.</p>
<p>Here are some tips to help you write accurate regular expressions:</p>
<ul>
<li><p><strong>Understand the string you want to match</strong>: before you write the regex pattern to match a string, examine the string closely. Determine if you're targeting the whole string or a particular part of the string. If you're targeting a part of the string or you want to strip out some, look out for the pattern that you want follow. If you get familiar with the string, you can write a more accurate regex.</p>
</li>
<li><p><strong>Be specific</strong>: avoid using the wildcard where necessary. For instance, do not use the wildcard to match a number since you can use <code>\d</code> or <code>[0-9]</code>, or uppercase letters since you can use <code>[A-Z]</code>.</p>
</li>
<li><p><strong>Use quantifiers to shorten patterns</strong>: if you want a particular part of your regex to match repeated occurrences, try to use quantifiers like <code>+</code>, <code>*</code>, <code>{n,m}</code>, <code>{n,}</code>, and <code>{n}</code>. For instance, if you want to match a date with <code>/</code> as the separator, you can use the pattern <code>\d{1,2}\/\d{1,2}\/\d{4}</code> instead of <code>\d\d\/\d\d\/\d\d\d\d</code>.</p>
</li>
<li><p><strong>Use online regex testers</strong>: online regex testers like regexpal.com and regex101.com help you write more accurate regexes by giving you a live match preview, highlighting matches, and showing you errors their engines encounter while processing the regexes.</p>
</li>
<li><p><strong>Use word boundary to prevent unwanted matches</strong>: surrounding your pattern with the word boundary (<code>\b</code>) can help you prevent unnecessary and unwanted matches. For example, if you want to match a 6-digit zip code, <code>\d{6}</code> can do it for you but will also match any part of the string that has 6 digits that follow one another. What would do it better is <code>\b\d{6}\b</code>.</p>
</li>
</ul>
<p>Anchors (<code>^</code> and <code>$</code>) can also help prevent unwanted matches since they "anchor" a pattern to the start or end of the line. You can use them to make sure the match is found at the end or start of the line, or both. </p>
<p>For example:</p>
<ul>
<li><code>/^Hello/i</code> would only match <code>Hello</code> or <code>hello</code> at the start of a line</li>
<li><code>/Hello$/i</code> would only match <code>Hello</code> or <code>hello</code> at the end of a line</li>
<li><code>/^Hello$/i</code> would only match <code>Hello</code> or <code>hello</code> if it’s the only target string unless you have the multiline flag turned on and there's <code>Hello</code> or <code>hello</code> on another line.</li>
</ul>
<p>If you have issues getting things right with a regex pattern, online testing tools like regex101.com and regexpal.com can also help you step through the pattern bit by bit. There are also regex visualizers you can use to check what's wrong with your regex patterns. </p>
<p>One of those tools that I find amazing is Regulex (jex.im/regulex). It helps you put your regular expressions in a visual perspective you can export</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/regulex-right.png" alt="regulex-right" width="600" height="400" loading="lazy"></p>
<p>And it can show you what goes wrong with your pattern:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/regulex-wrong.png" alt="regulex-wrong" width="600" height="400" loading="lazy"></p>
<h2 id="heading-chapter-9-applications-of-regular-expressions">Chapter 9: Applications of Regular Expressions</h2>
<h3 id="heading-a-better-way-to-match-dates">A Better Way to Match Dates</h3>
<p>You've seen several patterns you can use to match dates in the <code>dd/mm/yyyy</code> format such as <code>\d\d\/\d\d\/\d\d\d\d</code>, <code>\d\d[/.-]\d\d[/.-]\d\d\d\d/;</code>, and <code>\d{1,2}\/\d{1,2}\/\d{4}</code>.</p>
<p>The problem is that those three patterns just check for the occurrence of a number, and not a valid date. For example, invalid dates <code>99/89/2022</code> or <code>42/32/1909</code> would still match those patterns:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/invalid-date-matches.png" alt="invalid-date-matches" width="600" height="400" loading="lazy"></p>
<p>The solution is that you must account for the acceptable day, month, and year:</p>
<ul>
<li>the day can be 1 or 2 digits</li>
<li>the day cannot exceed 31</li>
<li>the month cannot exceed 12</li>
<li>the year could be 2 or 4 digits, but never 1, 3, or greater than 4 digits</li>
</ul>
<p>You should also account for:</p>
<ul>
<li>a day that could start with 0, 1, 2, or 3, but never 4 or greater</li>
<li>a month that could start with 0, or 1, but never 2 or greater</li>
</ul>
<p>Here's the regex pattern that satisfies those conditions:</p>
<pre><code class="lang-console">/^(3[01]|[12][0-9]|0?[1-9])[-./](1[0-2]|0?[1-9])[-./](20[0-9]{2}|[0-9]{4}|[0-9]{2})$/gm
</code></pre>
<p>The image below is an illustration that labels each part of the pattern and explains what they do:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/regexdate--1-.png" alt="regexdate--1-" width="600" height="400" loading="lazy"></p>
<p>Here are the dates that match the pattern and those that do not:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/date-re-matches.png" alt="date-re-matches" width="600" height="400" loading="lazy"></p>
<p>You can take the pattern and test it against some dates in JavaScript:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> re =
  <span class="hljs-regexp">/^(3[01]|[12][0-9]|0?[1-9])[-./](1[0-2]|0?[1-9])[-./](20[0-9]{2}|[0-9]{4}|[0-9]{2})$/</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">testDate</span>(<span class="hljs-params">date</span>) </span>{
  <span class="hljs-keyword">const</span> dateTester = re.test(date);
  <span class="hljs-built_in">console</span>.log(dateTester);
}

testDate(<span class="hljs-string">'12-01-2022'</span>); <span class="hljs-comment">// true</span>
testDate(<span class="hljs-string">'31.11.1999'</span>); <span class="hljs-comment">// true</span>
testDate(<span class="hljs-string">'02-01-21'</span>); <span class="hljs-comment">// true</span>
testDate(<span class="hljs-string">'42-01-2021'</span>); <span class="hljs-comment">// false</span>
testDate(<span class="hljs-string">'22-91-23'</span>); <span class="hljs-comment">// false</span>
</code></pre>
<p>You can see the date, month, year, and separator parts of the pattern are in their respective groups. If you want to match other formats like <code>mm/dd/yyyy</code> or <code>yyyy/mm/dd</code>, you can twist the pattern around.</p>
<p>You can even make the pattern a little shorter by putting the first separator in a group and referencing it for the second separator:</p>
<pre><code class="lang-console">^(3[01]|[12][0-9]|0?[1-9])([-./])(1[0-2]|0?[1-9])\2(20[0-9]{2}|[0-9]{4}|[0-9]{2})$
</code></pre>
<h3 id="heading-how-to-match-us-zip-codes">How to Match US Zip Codes</h3>
<p>The zip codes in the US are a 5-digit number, but they may also have a 4-digit extension, for example, <code>56893</code> or <code>56893-9232</code>.</p>
<p>The pattern <code>\b\d{5}\b</code> would match a 5-digit zip-code:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/zip-code-first-part-match.png" alt="zip-code-first-part-match" width="600" height="400" loading="lazy"></p>
<p>You also need to account for the other 4 digits and the hyphen between the two sets of numbers. The pattern, <code>\b\d{5}(\-\d{4})?\b</code> would do that for you.</p>
<p>Here's an image that labels each part of the pattern and explais what they do:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/zip-regex--1-.png" alt="zip-regex--1-" width="600" height="400" loading="lazy"></p>
<p>You can also take the regex and extract all the zip codes that are matches:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/\b\d{5}(\-\d{4})?\b/g</span>;
<span class="hljs-keyword">const</span> zipCodes = [
  <span class="hljs-string">'56893'</span>,
  <span class="hljs-string">'ca58392bn'</span>,
  <span class="hljs-string">'29043'</span>,
  <span class="hljs-string">'90342-9014'</span>,
  <span class="hljs-string">'89435'</span>,
  <span class="hljs-string">'75034'</span>,
  <span class="hljs-string">'90453-3056'</span>,
  <span class="hljs-string">'12345-6789'</span>,
  <span class="hljs-string">'b458923'</span>,
  <span class="hljs-string">'589323'</span>,
];

<span class="hljs-keyword">const</span> matchedZipCodes = [];

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> zipCode <span class="hljs-keyword">of</span> zipCodes) {
  <span class="hljs-keyword">const</span> matches = zipCode.match(re);
  <span class="hljs-keyword">if</span> (matches) {
    matchedZipCodes.push(matches[<span class="hljs-number">0</span>]);
  }
}

<span class="hljs-built_in">console</span>.log(matchedZipCodes);

<span class="hljs-comment">/*
Output:
[
  '56893',
  '29043',
  '90342-9014',
  '89435',
  '75034',
  '90453-3056',
  '12345-6789'
]
*/</span>
</code></pre>
<p>And if you want the zip codes that are invalid, you can use the <code>filter()</code> array method to remove those that do not match the pattern:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> re = <span class="hljs-regexp">/\b\d{5}(\-\d{4})?\b/g</span>;
<span class="hljs-keyword">const</span> zipCodes = [
  <span class="hljs-string">'56893'</span>,
  <span class="hljs-string">'ca58392bn'</span>,
  <span class="hljs-string">'29043'</span>,
  <span class="hljs-string">'90342-9014'</span>,
  <span class="hljs-string">'89435'</span>,
  <span class="hljs-string">'75034'</span>,
  <span class="hljs-string">'90453-3056'</span>,
  <span class="hljs-string">'12345-6789'</span>,
  <span class="hljs-string">'b458923'</span>,
  <span class="hljs-string">'589323'</span>,
];

<span class="hljs-keyword">const</span> invalidZipCodes = zipCodes.filter(<span class="hljs-function">(<span class="hljs-params">zipCode</span>) =&gt;</span> !zipCode.match(re));

<span class="hljs-built_in">console</span>.log(invalidZipCodes); <span class="hljs-comment">// [ 'ca58392bn', 'b458923', '589323' ]</span>
</code></pre>
<h3 id="heading-how-to-match-email-addresses">How to Match Email Addresses</h3>
<p>Email addresses could be as simple as <code>john@email.com</code>, and as complex as you can ever imagine. So, there's no "one pattern" for validating email addresses. This also makes email validation a complex thing to do.</p>
<p>Validating emails with regex can also be a bit questionable because you can't stop anyone from making an email up. But still, there's a format you generally want the email address to be in whether it is made up or not. This is why you may want to use regular expressions to validate an email.</p>
<p>A pattern like <code>^/\w{4,}@\w{3,}\.\w{3,}$/</code> could be enough for validating simple and straightforward email addresses like <code>john@example.com</code>.</p>
<p>Here's an image that labels each part of the pattern and explains what they do:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/simpleEmailRegEx.png" alt="simpleEmailRegEx" width="600" height="400" loading="lazy"></p>
<p>And here are the emails that match:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/email-unreliable.png" alt="email-unreliable" width="600" height="400" loading="lazy"></p>
<p>As you can see, the pattern did not even match all the emails provided. That's because the pattern does not account for:</p>
<ul>
<li>emails with a period within usernames like <code>jane.doe@email.com</code> </li>
<li>second-level domain (SLD) extensions like <code>john@example.abc.com</code> </li>
<li>and country code second-level domains (ccSLDs) like <code>jane@email.co.uk</code></li>
</ul>
<p>In fact, a single email can even combine all the criteria listed above.</p>
<p>A better pattern for matching emails is <code>/^[\w.-]+@[a-zA-Z\d.-]+\.[a-zA-Z]{2,}$/</code>. </p>
<p>I also prepare an illustration that labels each part of the pattern and shows what they do:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/betterEmailRegEx.png" alt="betterEmailRegEx" width="600" height="400" loading="lazy"></p>
<p>This pattern matches an email address better than the first one:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/email-a-bit-reliable.png" alt="email-a-bit-reliable" width="600" height="400" loading="lazy"></p>
<p>According to the RFC 5322 specification, the pattern that works 99% of the time for validating email is this:</p>
<pre><code class="lang-console">(?:[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
</code></pre>
<p><strong>N.B.</strong>: You should surround the pattern with anchors so it doesn’t leave out a part of a possible email and match the others. </p>
<p>This is what I'm trying to point out:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/matchingIvalidEmail.png" alt="matchingIvalidEmail" width="600" height="400" loading="lazy"></p>
<p>You can take that pattern into JavaScript and test it against some email addresses:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> emailRe =
  <span class="hljs-regexp">/^(?:[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">matchEmail</span>(<span class="hljs-params">email</span>) </span>{
  <span class="hljs-keyword">if</span> (emailRe.test(email)) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Valid email!'</span>);
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Invalid email'</span>);
  }
}

matchEmail(<span class="hljs-string">'janedoe@email.com'</span>);
matchEmail(<span class="hljs-string">'john.doe@email.com'</span>);
matchEmail(<span class="hljs-string">'7@koala@email.com!'</span>);
matchEmail(<span class="hljs-string">'kayla.simpson@email.co.uk'</span>);
matchEmail(<span class="hljs-string">'kayla.simpson@email.co..uk'</span>);
</code></pre>
<p>As I pointed out earlier, matching email addresses with regex is a complex task. If you know the kind of email you'll be working with, it is better to tailor your regex for them. </p>
<p>Sometimes, to match an email, all you all you might need is a simple regex. Some other times, the pattern you need might be as complex as the one above.</p>
<h3 id="heading-how-to-match-passwords">How to Match Passwords</h3>
<p>To match passwords, you can use a lookahead – since lookaround groups generally don’t consume characters. But there are always multiple ways of doing the same thing in regular expressions, and programming in general of course.</p>
<p>You've seen a lookahead for matching 6-digit passwords already. This time around, let's say the password should not be less than 8 characters with at least one uppercase, one lowercase, one digit, and one symbol.</p>
<p>Here's the regex pattern that does just that:</p>
<pre><code class="lang-console">^(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$?%"';^}{&amp;:*()∞+=-]).*$
</code></pre>
<p>Here are the passwords it matches:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/pword-matches.png" alt="pword-matches" width="600" height="400" loading="lazy"></p>
<p>You can take that into JavaScript and test it against possible passwords:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> passwordRe =
  <span class="hljs-regexp">/^(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$?%"';^}{&amp;:*()∞+=-]).*$/gm</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">matchPassWord</span>(<span class="hljs-params">password</span>) </span>{
  <span class="hljs-keyword">if</span> (passwordRe.test(password)) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-literal">true</span>);
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-literal">false</span>);
  }
}

matchPassWord(<span class="hljs-string">'johnDoe21^'</span>);
matchPassWord(<span class="hljs-string">'Strong@123'</span>);
matchPassWord(<span class="hljs-string">'weakpassword'</span>);
matchPassWord(<span class="hljs-string">'ABcd12$'</span>);
matchPassWord(<span class="hljs-string">'Longpassword1234!'</span>);
matchPassWord(<span class="hljs-string">'Short@1'</span>);
matchPassWord(<span class="hljs-string">'janEdoe34$'</span>);
</code></pre>
<p>You can also extract each of those group into its variable and test a password against it. This would let you show an error for that particular condition the password is trying to match:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> passwordLength = <span class="hljs-regexp">/(?=.{8,})/</span>,
  lowercaseChar = <span class="hljs-regexp">/(?=.*[a-z])/</span>,
  uppercaseChar = <span class="hljs-regexp">/(?=.*[A-Z])/</span>,
  numberChar = <span class="hljs-regexp">/(?=.*[0-9])/</span>,
  specialChar = <span class="hljs-regexp">/(?=.*[!@#$?%"';^}{&amp;:*()∞+=-])/</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">validatePassword</span>(<span class="hljs-params">password</span>) </span>{
  <span class="hljs-keyword">if</span> (
    passwordLength.test(password) &amp;&amp;
    lowercaseChar.test(password) &amp;&amp;
    uppercaseChar.test(password) &amp;&amp;
    numberChar.test(password) &amp;&amp;
    specialChar.test(password)
  ) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Valid password!'</span>);
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Invalid Password'</span>);
  }
}

validatePassword(<span class="hljs-string">'johnDoe21^'</span>);
validatePassword(<span class="hljs-string">'Strong@123'</span>);
validatePassword(<span class="hljs-string">'weakpassword'</span>);
validatePassword(<span class="hljs-string">'ABcd12$'</span>);
validatePassword(<span class="hljs-string">'Longpassword1234!'</span>);
validatePassword(<span class="hljs-string">'Short@1'</span>);
validatePassword(<span class="hljs-string">'janEdoe34$'</span>);
</code></pre>
<h3 id="heading-form-validation-with-regex">Form Validation with Regex</h3>
<p>One of the most popular ways developers use regular expressions is form validation. Since a form usually has input fields like name, email, password, and others, you can write a regular expression for what you expect the user to put in those input fields.</p>
<p>I prepared a little website where I show you how to validate the name, username, email, and password fields of a form with regex. </p>
<p>Here's the HTML:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"styles.css"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"form-validate.js"</span> <span class="hljs-attr">defer</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Form Validation with RegEx<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"error-message"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">""</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Sign Up<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Fill in the form fields<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-control"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"name"</span>&gt;</span>Name<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"name"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"name"</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-control"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"username"</span>&gt;</span>Username<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"username"</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-control"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"email"</span>&gt;</span>Email<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"email"</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-control"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"email"</span>&gt;</span>Password<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"password"</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Submit"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"submit"</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>The CSS:</p>
<pre><code class="lang-css"><span class="hljs-keyword">@import</span> url(<span class="hljs-string">'https://fonts.googleapis.com/css2?family=Roboto&amp;display=swap'</span>);

* {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">box-sizing</span>: border-box;
}

<span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#d0d0d5</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
  <span class="hljs-attribute">font-family</span>: <span class="hljs-string">'Roboto'</span>, sans-serif;
}

<span class="hljs-selector-tag">form</span> {
  <span class="hljs-attribute">position</span>: absolute;
  <span class="hljs-attribute">top</span>: <span class="hljs-number">50%</span>;
  <span class="hljs-attribute">left</span>: <span class="hljs-number">50%</span>;
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">translate</span>(-<span class="hljs-number">50%</span>, -<span class="hljs-number">50%</span>);
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#3b3b4f</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0.4rem</span> <span class="hljs-number">3rem</span> <span class="hljs-number">1rem</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">2px</span>;
}

<span class="hljs-selector-tag">p</span> {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0.5rem</span> <span class="hljs-number">0</span>;
}

<span class="hljs-selector-id">#error-message</span> {
  <span class="hljs-attribute">background-color</span>: crimson;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
  <span class="hljs-attribute">max-width</span>: <span class="hljs-number">80%</span>;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0.5rem</span> auto <span class="hljs-number">0</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0.2rem</span> <span class="hljs-number">0.5rem</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">4px</span>;
}

<span class="hljs-selector-id">#error-message</span> <span class="hljs-selector-tag">p</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">14px</span>;
  <span class="hljs-attribute">text-align</span>: center;
}

<span class="hljs-selector-class">.form-control</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-direction</span>: column;
}

<span class="hljs-selector-class">.form-control</span> <span class="hljs-selector-tag">label</span> {
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">0.2rem</span>;
}

<span class="hljs-selector-class">.form-control</span> <span class="hljs-selector-tag">input</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">14rem</span>;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">1.2rem</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0.2rem</span>;
  <span class="hljs-attribute">border</span>: <span class="hljs-number">2px</span> solid <span class="hljs-number">#d0d0d5</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">2px</span>;
}

<span class="hljs-selector-class">.form-control</span> <span class="hljs-selector-tag">input</span><span class="hljs-selector-pseudo">:focus</span> {
  <span class="hljs-attribute">outline</span>: none;
}

<span class="hljs-selector-tag">input</span><span class="hljs-selector-attr">[type=<span class="hljs-string">'submit'</span>]</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#fecc4c</span>;
  <span class="hljs-attribute">border-color</span>: <span class="hljs-number">#f1a02a</span>;
  <span class="hljs-attribute">font-family</span>: <span class="hljs-string">'Roboto'</span>, sans-serif;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0.3rem</span>;
  <span class="hljs-attribute">border-width</span>: <span class="hljs-number">1px</span>;
  <span class="hljs-attribute">cursor</span>: pointer;
}

<span class="hljs-selector-tag">input</span><span class="hljs-selector-attr">[type=<span class="hljs-string">'submit'</span>]</span><span class="hljs-selector-pseudo">:hover</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#e3bd53</span>;
}

<span class="hljs-selector-class">.hide</span> {
  <span class="hljs-attribute">display</span>: none;
}

<span class="hljs-selector-class">.show</span> {
  <span class="hljs-attribute">display</span>: block;
}

<span class="hljs-keyword">@media</span> screen <span class="hljs-keyword">and</span> (<span class="hljs-attribute">max-width:</span> <span class="hljs-number">768px</span>) {
  <span class="hljs-selector-id">#error-message</span> {
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">0.5rem</span> auto <span class="hljs-number">0</span>;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">0.1rem</span> <span class="hljs-number">0.2rem</span>;
  }
}

<span class="hljs-keyword">@media</span> screen <span class="hljs-keyword">and</span> (<span class="hljs-attribute">max-width:</span> <span class="hljs-number">667px</span>) {
  <span class="hljs-selector-tag">form</span> {
    <span class="hljs-attribute">top</span>: <span class="hljs-number">61%</span>;
  }

  <span class="hljs-selector-id">#error-message</span> {
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">0.2rem</span> auto <span class="hljs-number">0</span>;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">0.1rem</span> <span class="hljs-number">0.4rem</span>;
  }
}
</code></pre>
<p>Most importantly, some well-commented JavaScript that contains the patterns I used, and how I tested each of the patterns against the respective fields they correlate with:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Get the form element</span>
<span class="hljs-keyword">const</span> form = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'form'</span>);
<span class="hljs-comment">// Get the div element that shows the error(s)</span>
<span class="hljs-keyword">const</span> errorMessageDiv = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#error-message'</span>);

<span class="hljs-comment">// The RegEx patterns in a "patterns" object</span>
<span class="hljs-keyword">const</span> patterns = {
  <span class="hljs-attr">nameRe</span>: <span class="hljs-regexp">/^[a-zA-Z]{2,35}\s[a-zA-Z]{2,35}$/</span>, <span class="hljs-comment">// validates the name field</span>
  usernameRe: <span class="hljs-regexp">/^[a-zA-Z]{3,30}(\d{1,4})?$/</span>, <span class="hljs-comment">// validates the username field</span>
  emailRe: <span class="hljs-regexp">/^[\w.-]+@[a-zA-Z\d.-]+\.[a-zA-Z]{2,}$/</span>, <span class="hljs-comment">// validates the email field</span>
  passwordRe:
    <span class="hljs-regexp">/^(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$?%"';^}{&amp;:*()∞+=-]).*$/</span>, <span class="hljs-comment">// validates the password field</span>
};

<span class="hljs-comment">// Hide error message div when the page loads</span>
errorMessageDiv.style.display = <span class="hljs-string">'none'</span>;

<span class="hljs-comment">// Add a submit event to the form</span>
form.addEventListener(<span class="hljs-string">'submit'</span>, validateAndSubmitForm);

<span class="hljs-comment">// Form validation and submit function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">validateAndSubmitForm</span>(<span class="hljs-params">e</span>) </span>{
  e.preventDefault();

  <span class="hljs-comment">// Clear previous error messages</span>
  errorMessageDiv.innerHTML = <span class="hljs-string">''</span>;

  <span class="hljs-keyword">let</span> nameInputValue = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#name'</span>).value;
  <span class="hljs-keyword">let</span> usernameInputValue = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#username'</span>).value;
  <span class="hljs-keyword">let</span> emailInputValue = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#email'</span>).value;
  <span class="hljs-keyword">let</span> passwordInputValue = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#password'</span>).value;

  <span class="hljs-comment">// Validate Name</span>
  <span class="hljs-keyword">if</span> (!patterns.nameRe.test(nameInputValue)) {
    showError(<span class="hljs-string">'Name must have first name and last name separated by a space'</span>);
  }

  <span class="hljs-comment">// Validate Username</span>
  <span class="hljs-keyword">if</span> (!patterns.usernameRe.test(usernameInputValue)) {
    showError(
      <span class="hljs-string">'Username must have between 3 and 30 characters and can include up to 4 digits at the end'</span>
    );
  }

  <span class="hljs-comment">// Validate Email</span>
  <span class="hljs-keyword">if</span> (!patterns.emailRe.test(emailInputValue)) {
    showError(<span class="hljs-string">'Enter a valid email address'</span>);
  }

  <span class="hljs-comment">// Validate Password</span>
  <span class="hljs-keyword">if</span> (!patterns.passwordRe.test(passwordInputValue)) {
    showError(
      <span class="hljs-string">'Password must contain at least 8 characters, one lowercase letter, one uppercase letter, one digit, and one special character.'</span>
    );
  }

  <span class="hljs-comment">// If there are no error messages, the form is valid, so you can submit it</span>
  <span class="hljs-keyword">if</span> (errorMessageDiv.innerHTML === <span class="hljs-string">''</span>) {
    <span class="hljs-built_in">console</span>.log(nameInputValue);
    <span class="hljs-built_in">console</span>.log(usernameInputValue);
    <span class="hljs-built_in">console</span>.log(emailInputValue);
    <span class="hljs-built_in">console</span>.log(passwordInputValue);

    <span class="hljs-comment">// Hide the errorMessageDiv element since there are no errors</span>
    errorMessageDiv.style.display = <span class="hljs-string">'none'</span>;

    <span class="hljs-comment">// Greet user</span>
    alert(<span class="hljs-string">`Hi <span class="hljs-subst">${usernameInputValue}</span> 👋🏽 \nThanks for filling this form`</span>);

    <span class="hljs-comment">// Clear input fields with the reset() method</span>
    <span class="hljs-built_in">document</span>.forms[<span class="hljs-number">0</span>].reset();
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-comment">// Show the errorMessageDiv element if there are errors</span>
    errorMessageDiv.style.display = <span class="hljs-string">'block'</span>;
  }
}

<span class="hljs-comment">// The function responsible for showing error(s)</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">showError</span>(<span class="hljs-params">message</span>) </span>{
  <span class="hljs-keyword">const</span> errorMessageElement = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'p'</span>);

  errorMessageElement.innerText = message;
  errorMessageDiv.appendChild(errorMessageElement);
}
</code></pre>
<p>This is what the form does:
<img src="https://www.freecodecamp.org/news/content/images/2023/07/form-validation.gif" alt="form-validation" width="600" height="400" loading="lazy"></p>
<p>You can grab all the code in this <a target="_blank" href="https://github.com/Ksound22/regex-bk-form-validator">GitHub repo</a>.</p>
<h3 id="heading-article-table-of-contents-generator">Article Table of Contents Generator</h3>
<p>You can leverage the power of regular expressions to create a markdown table of contents generator.</p>
<p>Markdown tables of contents are made up of <code>h2</code> headings at the top level. Those <code>h2</code> headings have an <code>id</code> attribute you can use as the link. If you take a look at those <code>id</code> attributes, they are in the format below:</p>
<pre><code class="lang-console">[How to Do ABC on XYZ!!!](##howtodoabconxyz)
</code></pre>
<p>This means you need to:</p>
<ul>
<li>use the text as it is as the link text and surround them with curly braces</li>
<li>replace all spaces with an empty string</li>
<li>replace all symbols with an empty string</li>
<li>convert all the letters to lowercase</li>
<li>surround the new link with parenthesis</li>
</ul>
<p>The <code>replace()</code> and <code>lowerCase()</code> string methods will help you achieve those things.</p>
<p>Here's the HTML for the app:</p>
<pre><code class="lang-js">&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;

&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;link rel="stylesheet" href="styles.css"&gt;
    &lt;script src="toc.js" defer&gt;&lt;/script&gt;
    &lt;title&gt;TOC Generator&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;
    &lt;div class="alert" id="alert"&gt;
        Please enter some heading texts!
    &lt;/div&gt;

    &lt;h1&gt;Markdown Table of Content Generator for your Next Article&lt;/h1&gt;
    &lt;h2&gt;Paste in your headings to generate table of content&lt;/h2&gt;
    &lt;form action=""&gt;

        &lt;div class="form"&gt;
            &lt;div class="form-control"&gt;
                &lt;textarea name="toc" id="toc" cols="40" rows="15"&gt;&lt;/textarea&gt;
            &lt;/div&gt;

            &lt;div class="form-control"&gt;
                &lt;input type="submit" value="Generate" id="submit"&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/form&gt;

    &lt;div id="generated-toc"&gt;
        &lt;!-- &lt;p&gt;Lorem ipsum dolor sit amet consectetur.&lt;/p&gt;
        &lt;p&gt;Lorem ipsum dolor sit amet consectetur.&lt;/p&gt;
        &lt;p&gt;Lorem ipsum dolor sit amet consectetur.&lt;/p&gt;
        &lt;p&gt;Lorem ipsum dolor sit amet consectetur.&lt;/p&gt;
        &lt;p&gt;Lorem ipsum dolor sit amet consectetur.&lt;/p&gt;
        &lt;p&gt;Lorem ipsum dolor sit amet consectetur.&lt;/p&gt;
        &lt;p&gt;Lorem ipsum dolor sit amet consectetur.&lt;/p&gt; --&gt;
    &lt;/div&gt;

&lt;/body&gt;

&lt;/html&gt;
</code></pre>
<p>The CSS:</p>
<pre><code class="lang-js">@<span class="hljs-keyword">import</span> url(<span class="hljs-string">'https://fonts.googleapis.com/css2?family=Poppins&amp;family=Roboto&amp;display=swap'</span>);

* {
  <span class="hljs-attr">margin</span>: <span class="hljs-number">0</span>;
  padding: <span class="hljs-number">0</span>;
  box-sizing: border-box;
}

body {
  font-family: <span class="hljs-string">'Poppins'</span> sans-serif;
  background-color: #<span class="hljs-number">3</span>b3b4f;
  color: #fff;
}

h1 {
  margin-top: <span class="hljs-number">2</span>rem;
}

h1,
h2 {
  text-align: center;
  color: black;
  margin-bottom: <span class="hljs-number">1</span>rem;
  color: white;
}

form {
  max-width: <span class="hljs-number">90</span>%;
  margin: <span class="hljs-number">0</span> auto;
  background-color: #d0d0d5;
  padding: <span class="hljs-number">2</span>rem;
  border-radius: <span class="hljs-number">2</span>px;
}

.form-control {
  text-align: center;
}

textarea {
  <span class="hljs-attr">padding</span>: <span class="hljs-number">0.2</span>rem <span class="hljs-number">2</span>rem <span class="hljs-number">1</span>rem <span class="hljs-number">0.2</span>rem;
}

<span class="hljs-attr">textarea</span>:focus {
  <span class="hljs-attr">outline</span>: <span class="hljs-number">1</span>px solid #<span class="hljs-number">3</span>b3b4f;
}

input[type=<span class="hljs-string">'submit'</span>] {
  font-family: <span class="hljs-string">'Poppins'</span>, sans-serif;
  font-size: <span class="hljs-number">1.1</span>rem;
  border: none;
  background-color: #<span class="hljs-number">03732</span>e;
  color: #fff;
  padding: <span class="hljs-number">0.5</span>rem <span class="hljs-number">1</span>rem;
  border-radius: <span class="hljs-number">4</span>px;
  margin-top: <span class="hljs-number">1</span>rem;
  transition: <span class="hljs-number">0.3</span>s;
}

input[type=<span class="hljs-string">'submit'</span>]:hover {
  <span class="hljs-attr">cursor</span>: pointer;
  background-color: #<span class="hljs-number">00471</span>b;
}

#generated-toc {
  max-width: <span class="hljs-number">60</span>%;
  margin: <span class="hljs-number">1</span>rem auto;
  background-color: #d0d0d5;
  color: black;
  padding: <span class="hljs-number">2</span>rem;
  border-radius: <span class="hljs-number">2</span>px;
  text-align: left;
  font-size: <span class="hljs-number">1.1</span>rem;
  display: none;
}

.alert {
  <span class="hljs-attr">display</span>: none;
  margin: <span class="hljs-number">1</span>rem auto;
  max-width: <span class="hljs-number">20</span>%;
  text-align: center;
  padding: <span class="hljs-number">1</span>rem <span class="hljs-number">0</span>;
  border-radius: <span class="hljs-number">2</span>px;
  background-color: #eb7189;
  color: black;
}

@media screen and (max-width: <span class="hljs-number">768</span>px) {
  textarea {
    <span class="hljs-attr">width</span>: <span class="hljs-number">16</span>rem;
  }

  .alert {
    max-width: <span class="hljs-number">50</span>%;
  }
}
</code></pre>
<p>And the well-commented JavaScript:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> form = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'form'</span>);
<span class="hljs-keyword">const</span> generatedToc = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#generated-toc'</span>);
<span class="hljs-keyword">const</span> alert = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.alert'</span>);

<span class="hljs-comment">// Regular expressions to remove spaces and special characters</span>
<span class="hljs-keyword">const</span> spaceRe = <span class="hljs-regexp">/\s+/g</span>;
<span class="hljs-keyword">const</span> symRe = <span class="hljs-regexp">/[°?+*$∞^%$#@!.,©:&amp;;"=%'_\[\]–\/\\&lt;&gt;|÷™®)£(}{€¥¢—“”‘•~]/g</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">generateToc</span>(<span class="hljs-params">e</span>) </span>{
  e.preventDefault();

  <span class="hljs-comment">// Get the heading texts from the textarea</span>
  <span class="hljs-keyword">const</span> headingTexts = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#toc'</span>).value;

  <span class="hljs-keyword">if</span> (headingTexts === <span class="hljs-string">''</span>) {
    <span class="hljs-comment">// Alert the user to enter heading texts</span>
    alert.style.display = <span class="hljs-string">'block'</span>;

    <span class="hljs-comment">// hide the alert after 3 seconds</span>
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      alert.style.display = <span class="hljs-string">'none'</span>;
    }, <span class="hljs-number">3000</span>);

    <span class="hljs-comment">// hide generated table of content (if any) since the user is trying to paste in another one</span>
    generatedToc.style.display = <span class="hljs-string">'none'</span>;
    <span class="hljs-keyword">return</span>;
  }

  <span class="hljs-comment">// Split the heading texts into an array of lines</span>
  <span class="hljs-keyword">const</span> headingLines = headingTexts.split(<span class="hljs-string">'\n'</span>);

  <span class="hljs-comment">// Create an initial empty variable to save the table of content inside later</span>
  <span class="hljs-keyword">let</span> tocContent = <span class="hljs-string">''</span>;

  <span class="hljs-comment">// Loop through each line and generate the table of content items</span>
  headingLines.forEach(<span class="hljs-function">(<span class="hljs-params">headingLine</span>) =&gt;</span> {
    <span class="hljs-comment">// Remove any leading and/or trailing spaces from the line</span>
    headingLine = headingLine.trim();

    <span class="hljs-comment">// skip empty lines</span>
    <span class="hljs-keyword">if</span> (headingLine === <span class="hljs-string">''</span>) {
      <span class="hljs-keyword">return</span>;
    }

    <span class="hljs-comment">// Generate the TOC link based on the heading text(s)</span>
    <span class="hljs-keyword">const</span> markdownLink = headingLine
      .replace(spaceRe, <span class="hljs-string">''</span>) <span class="hljs-comment">// replace spaces with an empty string</span>
      .replace(symRe, <span class="hljs-string">''</span>) <span class="hljs-comment">// replace special characters (symbols)</span>
      .toLowerCase(); <span class="hljs-comment">// convert the link texts to lowercase characters</span>

    <span class="hljs-comment">// Create the table of contents item and append it to the tocContent variable</span>
    tocContent += <span class="hljs-string">`&lt;p&gt;• [<span class="hljs-subst">${headingLine}</span>](#<span class="hljs-subst">${markdownLink}</span>)&lt;/p&gt;`</span>;
  });

  <span class="hljs-comment">// Insert the generated table of contents into the "generated-toc" div element</span>
  generatedToc.innerHTML = tocContent;

  <span class="hljs-comment">// hide alert since there's currently no error at this point</span>
  alert.style.display = <span class="hljs-string">'none'</span>;

  <span class="hljs-comment">// show the "generated-toc" div</span>
  generatedToc.style.display = <span class="hljs-string">'block'</span>;

  <span class="hljs-comment">// clear the heading texts in the text area</span>
  <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#toc'</span>).value = <span class="hljs-string">''</span>;
}

<span class="hljs-comment">// Add a submit event to the form</span>
form.addEventListener(<span class="hljs-string">'submit'</span>, generateToc);

<span class="hljs-comment">/*
What is HTML?
How to Contribute$ To Open Source Like a Boss!!
Why you should Learn to C$ode in Java?

Why you should get into Web3!
Don't Attach Question Mark(?) to Hows!
Stop Scaring Newbies!
Why are you too cold&amp;
*/</span>
</code></pre>
<p>Here's what's happening in the app:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/tocgen.gif" alt="tocgen" width="600" height="400" loading="lazy"></p>
<p>You can look through the code to have more understanding of how I was able to do that. The code is available on this <a target="_blank" href="https://github.com/Ksound22/regex-bk-form-validator">GitHub repo</a> and the app is <a target="_blank" href="https://astonishing-dolphin-948101.netlify.app/">live here</a>.</p>
<h2 id="heading-glossary-and-references">Glossary and References</h2>
<h3 id="heading-glossary-of-terms">Glossary of Terms</h3>
<ul>
<li><code>Regular Expression</code> or <code>RegEx</code>: A you can use for matching, searching, and manipulating text.</li>
<li><code>Pattern</code> or <code>regex pattern</code>: A sequence of characters that defines a search criterion in a regular expression.</li>
<li><code>Literal Character</code>: A character that matches itself in a regular expression (for example, "a" matches the character "a").</li>
<li><code>Flag</code>: Modifiers added after the closing delimiter of a regex to change matching behavior, such as <code>i</code> (case-insensitive) or <code>g</code> (global).</li>
<li><code>Metacharacter</code>: A character with a special meaning in a regular expression. Examples include <code>.</code> (any character), <code>*</code> (zero or more), and <code>|</code> (alternation).</li>
<li><code>Quantifier</code>: A metacharacter that specifies the number of repetitions of the preceding element. For example, <code>*</code> matches zero or more occurrences, and <code>{n}</code> matches <code>n</code> character(s).</li>
<li><code>Anchors</code>: Metacharacters that represent positions in the input string, such as <code>^</code> (start of line) and <code>$</code> (end of line).</li>
<li><code>Grouping</code>: Using parentheses <code>()</code> to create a subexpression you can repeat or reference as a single unit.</li>
<li><code>Capture Group</code>: A group in a regular expression that captures and stores the matched text for later use.</li>
<li><code>Non-Capturing Group</code>: A group in a regular expression that matches the pattern but does not capture the matched text.</li>
<li><code>Greedy</code>: A matching behavior where quantifiers try to match as much as possible.</li>
<li><code>Lazy</code>: Another matching behavior where quantifiers match as little as possible. It is the opposite of <code>greedy</code>.</li>
<li><code>Lookahead</code>: A zero-width assertion that looks ahead to see if a pattern exists without including it in the match.</li>
<li><code>Lookbehind</code>: A zero-width assertion that looks behind to see if a pattern exists without including it in the match.</li>
<li><code>Escape Sequence and Character</code>: Using a backslash <code>\</code>to escape a metacharacter to treat it as a literal character. Or using it before a character to match its special meaning instead of the literal character. For example, <code>\d</code>.</li>
<li><code>Word Boundary</code>: A zero-width assertion that matches the position between a word character and a non-word character.</li>
<li><code>Negated Character Class</code>: A character class with <code>^</code> as the first character, matching any character not in the class.</li>
<li><code>Regex Engine</code>: The underlying software component that processes regular expressions and performs matching.</li>
<li><code>Case Sensitive</code>: A matching behavior where letters' cases must exactly match in the regex pattern and the input string.</li>
<li><code>Case Insensitive</code>: A flag (<code>i</code>) that enables case-insensitive matching in the regular expression.</li>
<li><code>Shorthand Character Class</code>: Shortcuts for common character classes, such as <code>\d</code> (digit), <code>\w</code> (word character), and <code>\s</code> (whitespace).</li>
<li>Backreference: Referring to a captured group's content in the regex pattern. For example, <code>\1</code>.</li>
<li>Alternation: Using the <code>|</code> metacharacter to match either of two patterns.</li>
<li>JavaScript RegExp Object: The built-in JavaScript object that represents a regular expression. It has methods like <code>test()</code> and <code>exec()</code> for working with regular expressions.</li>
<li><code>Regular Expression Literals</code>: Regular expressions defined using slashes <code>/.../</code>, e.g., <code>/regex-pattern/</code>.</li>
<li>RegExp Constructor: The RegExp constructor for creating regular expressions dynamically.</li>
</ul>
<h3 id="heading-quick-reference-of-metacharacters-and-quantifiers">Quick Reference of Metacharacters and Quantifiers</h3>
<ul>
<li><code>\d</code>: matches any digit (0-9).</li>
<li><code>\D</code>: matches any non-digit character.</li>
<li><code>\w</code>: matches any word character (alphanumeric characters and underscore).</li>
<li><code>\W</code>: matches any non-word character.</li>
<li><code>\s</code>: matches any whitespace character (space, tab, newline, carriage return).</li>
<li><code>\S</code>: matches any non-whitespace character.</li>
<li><code>\b</code>: matches a word boundary position.</li>
<li><code>\B</code>: matches a non-word boundary position.</li>
<li><code>^</code>: matches the start of the line.</li>
<li><code>$</code>: matches the end of the line.</li>
<li><code>.</code>: matches any character except newline.</li>
<li><code>*</code>: matches zero or more occurrences.</li>
<li><code>+</code>: matches one or more occurrences.</li>
<li><code>?</code>: matches zero or one occurrence.</li>
<li><code>{n}</code>: matches exactly <code>n</code> (number) occurrences.</li>
<li><code>{n,}</code>: matches <code>n</code> or more occurrences.</li>
<li><code>{n,m}</code> matches at least <code>n</code> and at most <code>m</code> (another number) occurrences.</li>
<li><code>|</code>: matches either the left or right expression.</li>
<li><code>(...)</code>: capturing group.</li>
<li><code>(?:...)</code>: non-capturing group.</li>
<li><code>\</code>: escapes a metacharacter in order to match it literally, or escapes a metacharacter that is also a literal character. For example, <code>\d</code>.</li>
<li><code>[...]</code>: character class.</li>
<li><code>[^...]</code>: negated character class.</li>
<li><code>(?=...)</code>:  positive lookahead.</li>
<li><code>(?!...)</code>: negative lookahead.</li>
<li><code>(?&lt;=...)</code> positive lookbehind.</li>
<li><code>(?&lt;!...)</code>: negative lookbehind.</li>
</ul>
<p>Thank you for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ RegEx for Date Formats – Regular Expressions for Matching Dates ]]>
                </title>
                <description>
                    <![CDATA[ Regular expressions let you match any string, be it in the form of various user inputs such as username, password, URL, and even different date formats. In this article, I’ll show you several ways you can match a date with regular expressions. In the... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/regex-for-date-formats-what-is-the-regular-expression-for-matching-dates/</link>
                <guid isPermaLink="false">66adf1f36f5e63db3fc43643</guid>
                
                    <category>
                        <![CDATA[ Regex ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Thu, 18 May 2023 12:41:17 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/dateRegEx.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Regular expressions let you match any string, be it in the form of various user inputs such as username, password, URL, and even different date formats.</p>
<p>In this article, I’ll show you several ways you can match a date with regular expressions.</p>
<p>In the programming world, there are always multiple ways of doing the same thing. So, how I’ll show you how to match date formats with regex might be different from how you’ll see it elsewhere.</p>
<h2 id="heading-what-well-cover">What We'll Cover</h2>
<ul>
<li><a class="post-section-overview" href="#heading-how-to-match-dates-with-regular-expressions">How to Match Dates with Regular Expressions</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-match-dates-with-regular-expressions-example-1">How to Match Dates with Regular Expressions – Example 1</a></li>
<li><a class="post-section-overview" href="#heading-how-to-match-dates-with-regular-expressions-example-2">How to Match Dates with Regular Expressions – Example 2</a></li>
<li><a class="post-section-overview" href="#heading-how-to-match-dates-with-regular-expressions-example-3">How to Match Dates with Regular Expressions – Example 3</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-how-to-match-dates-with-regular-expressions">How to Match Dates with Regular Expressions</h2>
<p>Dates are usually numbers unless you format them with some programming tools. So, the characters I will use to match dates will be digit characters.</p>
<h3 id="heading-how-to-match-dates-with-regular-expressions-example-1">How to Match Dates with Regular Expressions – Example 1</h3>
<p>Let’s start with something less complex first. Assuming the date format is in <code>DD/MM/YYYY</code> or <code>MM/DD/YYYY</code>, this would work:</p>
<pre><code class="lang-bash">\d{1,2}\/\d{1,2}\/\d{2,4}
</code></pre>
<p>In the regex above:</p>
<ul>
<li><code>\d{1,2}</code> matches 1 or 2 digits</li>
<li><code>\/</code> matches a slash (the separator). You can also make a hyphen (-) the separator</li>
<li>\d{2,4} matches 2 or 4 digits</li>
</ul>
<p>Indeed, the pattern matches a date:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/Screenshot-2023-05-18-at-11.08.02.png" alt="Screenshot-2023-05-18-at-11.08.02" width="600" height="400" loading="lazy"> </p>
<p>But that pattern is too generic because we don’t know which is which between the date and the month. The year can also be 2 or 4 digits. </p>
<p>In short, anything that is not a valid date would go:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/Screenshot-2023-05-18-at-11.11.10.png" alt="Screenshot-2023-05-18-at-11.11.10" width="600" height="400" loading="lazy"> </p>
<p>That’s not how you want to match a date. I’ll show you a better pattern next.</p>
<h3 id="heading-how-to-match-dates-with-regular-expressions-example-2">How to Match Dates with Regular Expressions – Example 2</h3>
<p>Here’s another pattern that can match a date:</p>
<pre><code class="lang-bash">(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[0,1,2])\/(19|20)\d{2}
</code></pre>
<p>In the pattern above: </p>
<ul>
<li><code>(0[1-9]|[12][0-9]|3[01])</code> is the first group of the pattern and it lets you specify the date only between <code>01</code> and <code>31</code></li>
<li><code>\/</code> is the separator</li>
<li><code>(0[1-9]|1[0,1,2])</code> represents the month and it lets you specify it between <code>01</code> and <code>12</code></li>
<li><code>\/</code> is another separator</li>
<li><code>(19|20)\d{2}</code> represents the year which can be between 1900 and any 2000 year</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/Screenshot-2023-05-18-at-11.37.38.png" alt="Screenshot-2023-05-18-at-11.37.38" width="600" height="400" loading="lazy"> </p>
<p>You can replace the separator with any hyphen this way:</p>
<pre><code class="lang-bash">(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[1,2])-(19|20)\d{2}
</code></pre>
<p>And you can accept both forward slash and hyphen as a separator:</p>
<pre><code class="lang-bash">(0[1-9]|[12][0-9]|3[01])(\/|-)(0[1-9]|1[1,2])(\/|-)(19|20)\d{2}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/Screenshot-2023-05-18-at-11.41.32.png" alt="Screenshot-2023-05-18-at-11.41.32" width="600" height="400" loading="lazy"></p>
<p>You can also rearrange the pattern to be in the <code>MM/DD/YYYY</code> format this way:</p>
<pre><code class="lang-bash">(0[1-9]|1[1,2])(\/|-)(0[1-9]|[12][0-9]|3[01])(\/|-)(19|20)\d{2}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/Screenshot-2023-05-18-at-11.46.46.png" alt="Screenshot-2023-05-18-at-11.46.46" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-match-dates-with-regular-expressions-example-3">How to Match Dates with Regular Expressions – Example 3</h3>
<p>Many times, you’ll be accepting just one date in your input. In that case, you have to specify the start and end of a string with caret (<code>^</code>) and dollar sign (<code>$</code>).</p>
<p>This is how I came with that pattern:</p>
<pre><code class="lang-bash">^(3[01]|[12][0-9]|0?[1-9])(\/|-)(1[0-2]|0?[1-9])\2([0-9]{2})?[0-9]{2}$
</code></pre>
<p>And here’s what the pattern does:</p>
<ul>
<li><code>^</code> denotes the start of the string</li>
<li><code>(3[01]|[12][0-9]|0?[1-9])</code> represents the day<ul>
<li><code>3[01]</code> matches numbers from <code>30</code> to <code>31</code></li>
<li><code>[12][0-9]</code> matches numbers from <code>10</code> to <code>29</code></li>
<li><code>0?[1-9]</code> matches numbers from <code>1</code> to <code>9</code>, with an optional leading zero</li>
</ul>
</li>
<li><code>(\/|-)</code> matches either a forward slash (<code>/</code>) or a hyphen (<code>-</code>)</li>
<li><code>(1[0-2]|0?[1-9])</code> represents the month part<ul>
<li><code>1[0-2]</code> matches numbers from <code>10</code> to <code>12</code></li>
<li><code>0?[1-9]</code> matches numbers from <code>1</code> to <code>9</code>, with an optional leading zero</li>
</ul>
</li>
<li><code>\2</code> is a backreference that matches the same delimiter captured in the second capturing group <code>(\/|-)</code>. This ensures that the delimiter between day and month is consistent</li>
<li><code>([0-9]{2})?</code> matches the two-digit year part optionally</li>
<li><code>([0-9]{2})</code> matches any two digits representing a year</li>
<li><code>[0-9]{2}</code> matches the last two digits of the year</li>
<li><code>$</code> denotes the end of the string</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This article took you through how to match a date with regular expressions with three examples.</p>
<p>The first example is a bit generic and won’t do well in matching a date, but the second can match valid dates in an input. The third does it better as it is tailored for a valid and single date – which would likely be what you want to do.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Regular Expressions in YAML File – RegEx in YAML Tutorial ]]>
                </title>
                <description>
                    <![CDATA[ YAML does not have built-in support for regular expressions. But you can still include regex patterns as part of a YAML file's contents, access those patterns, and create a regex out of them. You can do this, for example, with the JavaScript RegExp c... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-regular-expressions-in-yaml-file/</link>
                <guid isPermaLink="false">66adf1506f5e63db3fc43620</guid>
                
                    <category>
                        <![CDATA[ Regex ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Regular Expressions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ YAML ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Wed, 17 May 2023 14:48:51 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/yamlRe.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>YAML does not have built-in support for regular expressions. But you can still include regex patterns as part of a YAML file's contents, access those patterns, and create a regex out of them.</p>
<p>You can do this, for example, with the JavaScript <code>RegExp</code> constructor.</p>
<p>So, in YAML, regular expressions are typically represented as strings, using a specific syntax to define the pattern. For example, a YAML key-value pair that includes a regular expression pattern might look like this:</p>
<pre><code class="lang-bash">example:
pattern: ^[A-Za-z]+$
</code></pre>
<p>In this article, I'll show you how to write regular expressions inside a YAML file and access its entries in a JavaScript file. Let's take a look at what the YAML file is first.</p>
<h2 id="heading-what-well-cover">What We'll Cover</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-a-yaml-file">What is a YAML File?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-write-regular-expressions-in-a-yaml-file">How to Write Regular Expressions in a YAML File</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-import-a-yaml-file-in-javascript-and-use-it">How to Import a YAML File in JavaScript and Use it</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-what-is-a-yaml-file">What is a YAML File?</h2>
<p>YAML stands for YAML ain't markup language. It is a human and machine-readable data serialization file format. It is often used as configuration files, for data exchange, and for representing structured data in DevOps engineering.</p>
<p>YAML files use indentation and a concise syntax to define data structures such as lists, dictionaries (key-value pairs), and scalars (strings, numbers, booleans).</p>
<p>Each entry in a YAML file can be string, number, or Boolean, and other YAML-specific data types like scalars and lists. Here's a YAML file containing those data types:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># YAML Data Types Example</span>
<span class="hljs-comment"># -----------------------</span>

<span class="hljs-comment"># Scalars</span>
null_example: null           <span class="hljs-comment"># Null Scalar</span>
bool_example: <span class="hljs-literal">true</span>           <span class="hljs-comment"># Boolean Scalar</span>
int_example: 42              <span class="hljs-comment"># Integer Scalar</span>
float_example: 3.14          <span class="hljs-comment"># Float Scalar</span>
str_example: <span class="hljs-string">"Hello, YAML!"</span>  <span class="hljs-comment"># String Scalar</span>

<span class="hljs-comment"># Sequences (Arrays)</span>
seq_example:                 <span class="hljs-comment"># Sequence (Array)</span>
  - Apple
  - Orange
  - Banana

<span class="hljs-comment"># Mappings (Dictionaries)</span>
map_example:                 <span class="hljs-comment"># Mapping (Dictionary)</span>
  key1: value1
  key2: value2
  key3: value3

<span class="hljs-comment"># List (Sequence of Mappings)</span>
list_example:                <span class="hljs-comment"># List of Mappings (Sequence of Dictionaries)</span>
  - name: John
    age: 30
  - name: Jane
    age: 28
  - name: Bob
    age: 35
</code></pre>
<p>You can also put regular expressions right inside a YAML file. And that's what we'll look at next.</p>
<h2 id="heading-how-to-write-regular-expressions-in-a-yaml-file">How to Write Regular Expressions in a YAML File</h2>
<p>You can represent specific values in a YAML file as regular expressions. Below are some validation regex patterns:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># validator.yaml file</span>
password:
  pattern: ^(?!.*[\s])(?=.*[A-Z])(?=.*[a-z])(?=.*\d)[A-Za-z\d@$!%*<span class="hljs-comment">#?&amp;]{8,}$</span>
  description: |
    - At least 8 characters
    - At least one uppercase letter
    - At least one lowercase letter
    - At least one digit
    - Allowed special characters: @$!%*<span class="hljs-comment">#?&amp;</span>

nigerianPhoneNumber:
  pattern: ^(\+?234|0)[789]\d{9}$
  description: |
    - Nigerian phone number format
    - Starts with +234 or 0
    - Followed by 7, 8, or 9
    - Total of 11 digits

email:
  pattern: ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$
  description: |
    - Valid email address format
    - Example: example@example.com

username:
  pattern: ^[a-zA-Z0-9_-]{3,16}$
  description: |
    - Allowed characters: letters (upper and lower <span class="hljs-keyword">case</span>), numbers, underscore (_), and hyphen (-)
    - Minimum length: 3 characters
    - Maximum length: 16 characters
</code></pre>
<p>You can then import the YAML file into your JavaScript file and do what you want with it – for instance, create regular expressions out of those patterns and use them.</p>
<p>But that process is not straightforward. So that's the next thing you'll learn in this article.</p>
<h2 id="heading-how-to-import-a-yaml-file-in-javascript-and-use-it">How to Import a YAML File in JavaScript and Use it</h2>
<p>If you attempt to import any YAML file into a JavaScript file with the <code>import</code> syntax, like <code>import abc from file.yaml</code>, this is the kind of error you'll get:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/reYamlErr.png" alt="reYamlErr" width="600" height="400" loading="lazy"></p>
<p>Instead of doing it that way, you should create a <code>package.json</code> in your project directory by running <code>npm init -y</code> and install the <code>js-yaml</code> package by running <code>npm install js-yaml</code>.</p>
<p>After that, import the <code>fs</code> module of Node.js and the <code>js-yaml</code> package this way:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);
<span class="hljs-keyword">const</span> yaml = <span class="hljs-built_in">require</span>(<span class="hljs-string">'js-yaml'</span>);
</code></pre>
<p>The next thing you should do is read the <code>validator.yaml</code> file with the <code>readFileSync</code> method of the <code>fs</code> module and parse the YAML file with the <code>load()</code> method:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> yamlData = fs.readFileSync(<span class="hljs-string">'validator.yaml'</span>, <span class="hljs-string">'utf8'</span>);
<span class="hljs-keyword">const</span> parsedData = yaml.load(yamlData);
</code></pre>
<p>All that's left to do is to access any of the patterns, create a RegEx out of it, and use it. This is how I used the password pattern:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> passwordPattern = parsedData.password.pattern;
<span class="hljs-keyword">const</span> pwordValidator = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(passwordPattern);

<span class="hljs-keyword">const</span> myPassword = <span class="hljs-string">'reallyStrongPassword21!'</span>;
<span class="hljs-built_in">console</span>.log(pwordValidator.test(myPassword)); <span class="hljs-comment">//true</span>
</code></pre>
<p>Here's how I used the Nigerian phone number validator pattern:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> phonePattern = parsedData.nigerianPhoneNumber.pattern;

phoneValidator = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(phonePattern);

<span class="hljs-keyword">const</span> myPhoneNum = <span class="hljs-string">'08133333333'</span>;
<span class="hljs-built_in">console</span>.log(phoneValidator.test(myPhoneNum)); <span class="hljs-comment">//true;</span>
</code></pre>
<p>Here's the full code:</p>
<pre><code class="lang-js"><span class="hljs-comment">// import the fs module to be able to access the YAML file</span>
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);

<span class="hljs-comment">// import the YAML package</span>
<span class="hljs-keyword">const</span> yaml = <span class="hljs-built_in">require</span>(<span class="hljs-string">'js-yaml'</span>);

<span class="hljs-comment">// Read the validator.yaml file with the FS module</span>
<span class="hljs-keyword">const</span> yamlData = fs.readFileSync(<span class="hljs-string">'test.yaml'</span>, <span class="hljs-string">'utf8'</span>);

<span class="hljs-comment">// parse the YAML file</span>
<span class="hljs-keyword">const</span> parsedData = yaml.load(yamlData);

<span class="hljs-comment">// Access the password validator pattern from the YAML file</span>
<span class="hljs-keyword">const</span> passwordPattern = parsedData.password.pattern;

<span class="hljs-comment">// Create a regex out of the password pattern</span>
<span class="hljs-keyword">const</span> pwordValidator = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(passwordPattern);

<span class="hljs-keyword">const</span> myPassword = <span class="hljs-string">'reallyStrongPassword21!'</span>;
<span class="hljs-built_in">console</span>.log(pwordValidator.test(myPassword)); <span class="hljs-comment">//true</span>

<span class="hljs-comment">// Access the nigeriaPhoneNumber validator pattern from the YAML file</span>
<span class="hljs-keyword">const</span> phonePattern = parsedData.nigerianPhoneNumber.pattern;

<span class="hljs-comment">// Create a regex out of the phonePAttern</span>
phoneValidator = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(phonePattern);

<span class="hljs-keyword">const</span> myPhoneNum = <span class="hljs-string">'08133333333'</span>;
<span class="hljs-built_in">console</span>.log(phoneValidator.test(myPhoneNum)); <span class="hljs-comment">//true;</span>

<span class="hljs-comment">// Access the email validator pattern from the YAML file</span>
<span class="hljs-keyword">const</span> emailPattern = parsedData.email.pattern;

<span class="hljs-comment">// Create a regex out of the phonePAttern</span>
emailValidator = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(emailPattern);

<span class="hljs-keyword">const</span> emailAddress = <span class="hljs-string">'chris@gmail.com'</span>;
<span class="hljs-built_in">console</span>.log(emailValidator.test(emailAddress)); <span class="hljs-comment">//false;</span>

<span class="hljs-comment">// Access the username validator pattern from the YAML file</span>
<span class="hljs-keyword">const</span> usernamePattern = parsedData.username.pattern;

<span class="hljs-comment">// Create a regex out of the phonePAttern</span>
usernameValidator = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(usernamePattern);

<span class="hljs-keyword">const</span> username = <span class="hljs-string">'ksound22'</span>;
<span class="hljs-built_in">console</span>.log(usernameValidator.test(username)); <span class="hljs-comment">//false;</span>
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This article showed you how to put regular expressions in a YAML file, import it into a JavaScript file with the <code>js-yaml</code> package, and access any of the values in it.</p>
<p>We also looked at how you can create regular expressions out of the patterns in the YAML file and test them with some strings.</p>
<p>Thanks for reading. If you find the article helpful, kindly share it with your friends and family.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ URL RegEx Pattern – How to Write a Regular Expression for a URL ]]>
                </title>
                <description>
                    <![CDATA[ Regular expressions provide a powerful and flexible way to define patterns and match specific strings, be it usernames, passwords, phone numbers, or even URLs. In this article, I'll show you the fundamentals of crafting a regular expression for URLs.... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-write-a-regular-expression-for-a-url/</link>
                <guid isPermaLink="false">66adf152db5636c0b30cba7d</guid>
                
                    <category>
                        <![CDATA[ Regex ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Mon, 15 May 2023 12:22:48 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/urlRegEx.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Regular expressions provide a powerful and flexible way to define patterns and match specific strings, be it usernames, passwords, phone numbers, or even URLs.</p>
<p>In this article, I'll show you the fundamentals of crafting a regular expression for URLs. Whether you need to validate user input, extract components from URLs, or perform any other URL-related tasks, understanding how to construct a regex for URLs can greatly enhance URL validation in your applications.</p>
<p>First, let me show you what a URL is.</p>
<h2 id="heading-what-well-cover">What We'll Cover</h2>
<ul>
<li><a class="post-section-overview" href="#heading-what-is-a-url">What is a URL?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-write-a-regular-expression-for-a-url">How to Write a Regular Expression for a URL</a></li>
<li><a class="post-section-overview" href="#heading-testing-the-regex-with-javascript">Testing the RegEx with JavaScript</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-what-is-a-url">What is a URL?</h2>
<p>A URL, short for Uniform Resource Locator, is a string that identifies the location of a resource on the web. It typically consists of various components, including:</p>
<ul>
<li>the protocol – for instance, HTTP or HTTPS</li>
<li>domain name – for example, freecodecamp.org</li>
<li>subdomain – for example, Chinese.freecodecamp.org</li>
<li>port number – 3000, 5000, 4000, and more</li>
<li>path – for example, <code>freecodecamp.org/news</code></li>
<li>query parameters – for example, <code>https://example.com/search?q=apple&amp;category=fruits</code></li>
</ul>
<h2 id="heading-how-to-write-a-regular-expression-for-a-url">How to Write a Regular Expression for a URL</h2>
<p>A URL can be a base URL (without a subdomain, path, or query param). It can also contain a subdomain, path, or other components. Due to this, you have to tailor your regular expression to the way you're expecting the URL.</p>
<p>If the users are typing in a base URL, you have to tailor your regex fir that, and if you're expecting a URL that has a subdomain or path, you have to tailor your regex that way. If you like, you can also write a complex regex that can accept a URL in any form it can come. It is not impossible.</p>
<p>Here's a regex pattern that matches a base URL of any domain extension:</p>
<pre><code class="lang-bash">(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)?[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?
</code></pre>
<p>This would match domains like <code>https://www.freecodecamp.org</code>, <code>http://www.freecodecamp.org/</code>, <code>freeCodeCamp.org</code>, <code>google.co.uk</code>, <code>facebook.net</code>, <code>google.com.ng</code>, <code>google.com.in</code>, and many other base URLs.</p>
<p>The pattern below matches any URL with a path:</p>
<pre><code class="lang-bash">(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)?[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?\/[a-zA-Z0-9]{2,}
</code></pre>
<p>This include URLs like <code>https://www.freecodecamp.org/news</code>,
<code>http://www.freecodecamp.org/ukrainian</code>, and others</p>
<p>If you want to match a URL with a subdomain, the pattern below can do it for you:</p>
<pre><code class="lang-js">(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)?[a-zA-Z0<span class="hljs-number">-9</span>]{<span class="hljs-number">2</span>,}\.[a-zA-Z0<span class="hljs-number">-9</span>]{<span class="hljs-number">2</span>,}\.[a-zA-Z0<span class="hljs-number">-9</span>]{<span class="hljs-number">2</span>,}(\.[a-zA-Z0<span class="hljs-number">-9</span>]{<span class="hljs-number">2</span>,})?
</code></pre>
<p>This would match subdomains like <code>https://www.chinese.freecodecamp.org</code>,
<code>chinese.freecodecamp.org</code>, <code>https://chinese.freecodecamp.org</code>, and others.</p>
<p>If you want a regex that matches any URL that is base, has a subdomain, or a path, you can combine all the patterns I've shown you like this:</p>
<pre><code class="lang-bash">(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)?[a-zA-Z]{2,}(\.[a-zA-Z]{2,})(\.[a-zA-Z]{2,})?\/[a-zA-Z0-9]{2,}|((https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)?[a-zA-Z]{2,}(\.[a-zA-Z]{2,})(\.[a-zA-Z]{2,})?)|(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)?[a-zA-Z0-9]{2,}\.[a-zA-Z0-9]{2,}\.[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})?
</code></pre>
<p>Not the prettiest way to do things, but it works:
<img src="https://www.freecodecamp.org/news/content/images/2023/05/ss1-5.png" alt="ss1-5" width="600" height="400" loading="lazy"></p>
<h2 id="heading-testing-the-regex-with-javascript">Testing the RegEx with JavaScript</h2>
<p>On testing the regex using the <code>test()</code> method of JavaScript RegEx, I got <code>true</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> pattern =
  <span class="hljs-regexp">/(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)?[a-zA-Z]{2,}(\.[a-zA-Z]{2,})(\.[a-zA-Z]{2,})?\/[a-zA-Z0-9]{2,}|((https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)?[a-zA-Z]{2,}(\.[a-zA-Z]{2,})(\.[a-zA-Z]{2,})?)|(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)?[a-zA-Z0-9]{2,}\.[a-zA-Z0-9]{2,}\.[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})?/g</span>;

<span class="hljs-keyword">const</span> urls = <span class="hljs-string">`https://www.freecodecamp.org
http://www.freecodecamp.org
google.co.uk
facebook.net
google.com.ng
google.com.in
freecodecamp.org
yoruba.freecodecamp.org
freecodecamp.org/yoruba

http://www.freecodecamp.org/news
freecodecamp.org/news

chinese.freecodecamp.org
https://chinese.freecodecamp.org`</span>;

<span class="hljs-built_in">console</span>.log(pattern.test(urls)); <span class="hljs-comment">//true;</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/ss2-2.png" alt="ss2-2" width="600" height="400" loading="lazy"></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The regular expression patterns for matching a URL depend on your specific need – since URLs can be in various forms. So, while writing the patterns for the URL, you have to write them to suit the way you expect the URL.</p>
<p>Writing a regex that matches all kinds of URLs works, but it's not the best way to because it's very hard to read and debug.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Find and Replace in Notepad++ – How to Find String with Regular Expression in Notepad++ ]]>
                </title>
                <description>
                    <![CDATA[ Notepad++ has a Find feature with which you can search for any text in a file. But it doesn’t end there.  You can also use Notepad++'s Find and Replace feature to search for a text and replace it with a specified replacement. The Find and Find and Re... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-find-string-with-regular-expression-in-notepad-find-and-replace-in-notepad/</link>
                <guid isPermaLink="false">66adf1196778e7bd69427bfe</guid>
                
                    <category>
                        <![CDATA[ Regex ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Fri, 05 May 2023 13:21:02 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/findAndReplacewithRe.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Notepad++ has a <strong>Find</strong> feature with which you can search for any text in a file. But it doesn’t end there. </p>
<p>You can also use Notepad++'s <strong>Find and Replace</strong> feature to search for a text and replace it with a specified replacement.</p>
<p>The <strong>Find</strong> and <strong>Find and Replace</strong> features accept regular text, but they both also accept regular expressions.</p>
<p>Let's see how the <strong>Find</strong> and <strong>Find and Replace</strong> feature of Notepad++ works by using regular expressions instead of regular text.</p>
<h2 id="heading-how-to-find-a-string-with-regular-expressions-in-notepad">How to Find a String with Regular Expressions in Notepad++</h2>
<p>This is the code I'll use for this demo:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Find String with RegEx in Notepad++<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Find String with RegEx in Notepad++<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Lorem ipsum dolor sit.<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
      Lorem ipsum dolor sit amet consectetur, adipisicing elit. Eius beatae
      dignissimos alias quo odit aperiam laborum accusamus ea maxime dolores?
    <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>Lorem ipsum dolor sit amet.<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Lorem ipsum dolor sit.<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Quae voluptatem
      perferendis iure laborum inventore ducimus harum saepe voluptatibus neque
      earum?
    <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>Lorem ipsum dolor sit amet.<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Lorem ipsum dolor sit.<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
      Lorem ipsum dolor, sit amet consectetur adipisicing elit. Magnam
      accusantium placeat dolore illo, quidem suscipit. Recusandae corrupti
      assumenda soluta libero!
    <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>Lorem ipsum dolor sit amet.<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Lorem ipsum dolor sit.<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
      Lorem ipsum dolor sit amet consectetur, adipisicing elit. Cupiditate
      officia rerum id inventore sunt deleniti quaerat quibusdam libero vero
      non?
    <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>Lorem ipsum dolor sit amet.<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Once you've opened your file in Notepad++, press <code>CTRL + H</code> to open the <strong>Find</strong> popup. Make sure you're in the <strong>Find</strong> tab because the <strong>Replace</strong> tab is what opens by default. </p>
<p>After that, select <strong>Regular expression</strong>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/ss1-3.png" alt="ss1-3" width="600" height="400" loading="lazy"> </p>
<p>Next, enter your regular expression in the search input. I want to search for all Heading elements, so I'll enter the regex <code>&lt;h(1|2|3|4|5|6)&gt;</code></p>
<p>After entering the regex, click the Find Next button. It may also appear as "Find":</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/ss2-1.png" alt="ss2-1" width="600" height="400" loading="lazy"> </p>
<p>To keep seeing the matches, you have to keep clicking the "Find Next" button. However, you can click the "Count" button to see all your matches:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/ss3-1.png" alt="ss3-1" width="600" height="400" loading="lazy"> </p>
<h2 id="heading-how-to-find-and-replace-a-string-with-regular-expressions-in-notepad">How to Find and Replace a String with Regular Expressions in Notepad++</h2>
<p>You can perform find and replace almost the same way. The only difference is that you select the "Replace" tab instead of "Find":</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/ss4-1.png" alt="ss4-1" width="600" height="400" loading="lazy"></p>
<p>The search regex gets automatically populated, so what you need to do here is specify what to replace the matches with and the click <strong>Replace</strong>. </p>
<p>Let's say I want to replace all headings with a <code>p</code> tag:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/ss5-2.png" alt="ss5-2" width="600" height="400" loading="lazy"> </p>
<p>Instead of clicking "Replace" repeatedly to replace the matches, you can click the "Replace All" button:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/ss6-1.png" alt="ss6-1" width="600" height="400" loading="lazy"> </p>
<p>I'm also going to find all the closing heading tags with this regex <code>&lt;\/h(1|2|3|4|5|6)&gt;</code> and replace them with closing <code>p</code> tags.</p>
<p>Now, this is what the code looks like:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Find String with RegEx in Notepad++<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Find String with RegEx in Notepad++<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Lorem ipsum dolor sit.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
      Lorem ipsum dolor sit amet consectetur, adipisicing elit. Eius beatae
      dignissimos alias quo odit aperiam laborum accusamus ea maxime dolores?
    <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Lorem ipsum dolor sit amet.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Lorem ipsum dolor sit.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Quae voluptatem
      perferendis iure laborum inventore ducimus harum saepe voluptatibus neque
      earum?
    <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Lorem ipsum dolor sit amet.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Lorem ipsum dolor sit.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
      Lorem ipsum dolor, sit amet consectetur adipisicing elit. Magnam
      accusantium placeat dolore illo, quidem suscipit. Recusandae corrupti
      assumenda soluta libero!
    <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Lorem ipsum dolor sit amet.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Lorem ipsum dolor sit.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
      Lorem ipsum dolor sit amet consectetur, adipisicing elit. Cupiditate
      officia rerum id inventore sunt deleniti quaerat quibusdam libero vero
      non?
    <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Lorem ipsum dolor sit amet.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Find and Replace is a great feature that saves you a ton of time in Notepad++, especially if you have to replace text in a large file.</p>
<p>Since VS Code is the most popular code editor these days, it also has its own find and replaces feature you can access by pressing <code>CTRL + H</code>. And if you want to search with regex, you can press the <code>.*</code> button:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/05/ss7-1.png" alt="ss7-1" width="600" height="400" loading="lazy"></p>
<p>Thank you for reading. </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is Punct in RegEx? How to Match All Punctuation Marks in Regular Expressions ]]>
                </title>
                <description>
                    <![CDATA[ In regular expressions, "punct" means punctuation marks. It is all non-word and non-space characters. "Punct" is a predefined character class in regular expressions, and you can use it in any regex flavor that supports it.  The Punct character class ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-punct-in-regex-how-to-match-all-punctuation-marks-in-regular-expressions/</link>
                <guid isPermaLink="false">66adf280febac312b73075de</guid>
                
                    <category>
                        <![CDATA[ Regex ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Fri, 28 Apr 2023 11:28:37 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/matchPunctuationRegEx.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In regular expressions, "punct" means punctuation marks. It is all non-word and non-space characters. "Punct" is a predefined character class in regular expressions, and you can use it in any regex flavor that supports it. </p>
<p>The <code>Punct</code> character class is denoted by <code>\p{Punct}</code> or simply <code>\p{P}</code>. It matches any punctuation mark in a string. This includes characters such as periods, commas, exclamation marks, and quotation marks. </p>
<p>Since there’s a way you can match all punctuation marks, that’s what we are going to look at in this article.</p>
<h2 id="heading-how-to-match-all-punctuation-marks-in-regex-engines">How to Match all Punctuation Marks in RegEx Engines</h2>
<p>Few regex engines out there have regex flavors that support <code>\p{P}</code>. So, for those that support it, <code>\p{P}</code> would match all punctuation marks in them.
<img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-28-at-08.07.14.png" alt="Screenshot-2023-04-28-at-08.07.14" width="600" height="400" loading="lazy"></p>
<p>For regex engines that don’t support <code>\p{P}</code>, you can match all punctuation marks by negating word characters and space characters with the pattern <code>[^\w\s]+</code>:
<img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-28-at-08.10.24.png" alt="Screenshot-2023-04-28-at-08.10.24" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-match-all-punctuation-marks-in-javascript-regex">How to Match all Punctuation Marks in JavaScript RegEx</h2>
<p>If you want to use the pattern <code>\p{P}</code> to match all punctuation marks in JavaScript, you have to assign it the Unicode flag like this <code>/\p{P}/u</code>. Otherwise, it won’t work. Let’s see that in action:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> text = <span class="hljs-string">`That said, Kolade, you don't have to forget to take home things you buy at the store again. Do you understand?

I just said that to show you that the pattern really matches punctuation marks. I don't forget things at the store. Here are other punctuation marks:! " # $ % &amp; ' ( ) * + , - . / : ; | &lt; = &gt; { } ? @ [ \ ] ^ _ `</span>;

<span class="hljs-keyword">const</span> regex1 = <span class="hljs-regexp">/\p{P}/gu</span>;
<span class="hljs-keyword">const</span> regex2 = <span class="hljs-regexp">/[^\w\s]+/g</span>;

<span class="hljs-built_in">console</span>.log(regex1.test(text)); <span class="hljs-comment">//true</span>
<span class="hljs-built_in">console</span>.log(regex2.test(text)); <span class="hljs-comment">//true</span>

<span class="hljs-built_in">console</span>.log(regex1.exec(text));
<span class="hljs-built_in">console</span>.log(regex2.exec(text));
</code></pre>
<p>Since <code>exec()</code> would only return one match and <code>test()</code> would only return a Boolean, you can loop through the matches with <code>exec()</code> and <code>while</code> loop to see all of them:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> text = <span class="hljs-string">`That said, Kolade, you don't have to forget to take home things you buy at the store again. Do you understand?

I just said that to show you that the pattern really matches punctuation marks. I don't forget things at the store. Here are other punctuation marks:! " # $ % &amp; ' ( ) * + , - . / : ; | &lt; = &gt; { } ? @ [ \ ] ^ _ `</span>;

<span class="hljs-keyword">const</span> regex1 = <span class="hljs-regexp">/\p{P}/gu</span>;
<span class="hljs-keyword">const</span> regex2 = <span class="hljs-regexp">/[^\w\s]+/g</span>;

<span class="hljs-keyword">let</span> match;

<span class="hljs-keyword">while</span> ((match = regex1.exec(text)) !== <span class="hljs-literal">null</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'A match: '</span>, match[<span class="hljs-number">0</span>], <span class="hljs-string">'at index: '</span>, match.index);
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-28-at-08.28.30.png" alt="Screenshot-2023-04-28-at-08.28.30" width="600" height="400" loading="lazy"></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>That’s how you can match all punctuation marks in regex engines and JavaScript. Don’t forget that if you’re using <code>\p{P}</code> to match punctuation marks, you have to use it with the Unicode flag like this <code>/\p{P}/u</code>. You can also apply the same to other programming languages.</p>
<p>If you want to learn more about regular expressions, you can use <a target="_blank" href="https://www.youtube.com/watch?v=ZfQFUJhPqMM">this video</a> made by Beau Carnes of freeCodeCamp.</p>
<p>Keep coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How do I Enable Square Brackets in RegEx? ]]>
                </title>
                <description>
                    <![CDATA[ In this article, you’ll learn about what square brackets do in regular expressions, how to use them for specifying ranges, and how to match them as a character. What Does Square Bracket Do in RegEx? In regular expressions, square brackets ([ ]) are c... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-do-i-enable-square-brackets-in-regex/</link>
                <guid isPermaLink="false">66adf0eeb0efb2bf012fd7c1</guid>
                
                    <category>
                        <![CDATA[ Regex ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Thu, 27 Apr 2023 12:31:45 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/regexSquareBrackets.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this article, you’ll learn about what square brackets do in regular expressions, how to use them for specifying ranges, and how to match them as a character.</p>
<h2 id="heading-what-does-square-bracket-do-in-regex">What Does Square Bracket Do in RegEx?</h2>
<p>In regular expressions, square brackets (<code>[ ]</code>) are characters that have a special meaning of their own. Since they have a special meaning, you can call them "metacharacter".  Square brackets help you to define a character set, which is a set of characters you want to match.</p>
<p>For example, <code>[aeiou]</code> would match all vowels</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-27-at-11.44.03.png" alt="Image" width="600" height="400" loading="lazy">
<em>Vowel Matches with Square Brackets in RegEx</em></p>
<p>In addition to that, some characters may have special meanings inside square brackets.</p>
<p>For instance, if you put a caret (<code>^</code>) before any other character inside square brackets, it means you’re negating the characters that follow the caret. That is, <strong>you’re telling the regex engine or your programming language not to match those characters</strong>.</p>
<p>In the screenshot below, I matched all non-vowels and spaces by negating all vowels inside a square bracket.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-27-at-11.44.47.png" alt="Image" width="600" height="400" loading="lazy">
<em>Negating all Non-Vowels and Spaces with Square Brackets in RegEx</em></p>
<p>In another instance, if you put in hyphen (<code>-</code>) between two characters inside square brackets, it means <strong>range</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-27-at-11.47.35.png" alt="Image" width="600" height="400" loading="lazy">
<em>Specifying Range with Square Brackets in RegEx</em></p>
<p>But there are some situations where you want to match the square brackets as a character of their own. Let’s look at how to do that next – the purpose of this article.</p>
<h2 id="heading-how-to-enable-square-brackets-in-regex">How to Enable Square Brackets in RegEx</h2>
<p>If you find yourself in a situation where you want to match square brackets, for example, like you have to do when matching special characters for passwords, <strong>you need to escape them</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-27-at-11.50.20.png" alt="Image" width="600" height="400" loading="lazy">
<em>Matching Square Brackets in RegEx</em></p>
<h2 id="heading-how-to-use-square-brackets-and-enable-them-in-javascript">How to Use Square Brackets and Enable them in JavaScript</h2>
<p>JavaScript works fine with square brackets as metacharacters and a character of their own.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> text =
  <span class="hljs-string">'This is the opening square bracket [ and this is the closing square bracket ] Both [ and ] are everyday part of regex'</span>;

<span class="hljs-keyword">const</span> regex = <span class="hljs-regexp">/\[|\]/g</span>;

<span class="hljs-built_in">console</span>.log(regex.test(text)); <span class="hljs-comment">//true</span>
</code></pre>
<p>You can take it further and loop through the matches by using the <code>exec()</code> method and <code>while</code> loop:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> text =
  <span class="hljs-string">'This is the opening square bracket [ and this is the closing square bracket ] Both [ and ] are everyday part of regex'</span>;

<span class="hljs-keyword">const</span> regex = <span class="hljs-regexp">/\[|\]/g</span>;

<span class="hljs-keyword">let</span> match;
<span class="hljs-keyword">while</span> ((match = regex.exec(text)) !== <span class="hljs-literal">null</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'A match:'</span>, match[<span class="hljs-number">0</span>], <span class="hljs-string">'at Index:'</span>, match.index);
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-27-at-12.14.23.png" alt="Screenshot-2023-04-27-at-12.14.23" width="600" height="400" loading="lazy"></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This article showed you how to use square brackets as metacharacters and a character of their own in Regex engines and JavaScript.</p>
<p>It's important to keep in mind that some programming languages or regex engines may have slightly different syntax or rules for using square brackets and other metacharacters in regex. So, if you’re using square brackets with other regex engines and programming languages apart from JavaScript, make sure you understand how they work with the square brackets.</p>
<p>Keep coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What Does M Mean in Regular Expressions? M Flag for RegEx ]]>
                </title>
                <description>
                    <![CDATA[ In regular expressions, "m" is a flag that signifies multiple lines. So, it is popularly called the "multiline flag". In this article, I will show you what the "m" flag does and how you can use it in both regex engines and JavaScript. What Does the "... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-does-m-mean-in-regular-expressions-m-flag-for-regex/</link>
                <guid isPermaLink="false">66adf251db5636c0b30cba9e</guid>
                
                    <category>
                        <![CDATA[ Regex ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Wed, 26 Apr 2023 14:31:31 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/mFlagRegex.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In regular expressions, "m" is a flag that signifies multiple lines. So, it is popularly called the "multiline flag".</p>
<p>In this article, I will show you what the "m" flag does and how you can use it in both regex engines and JavaScript.</p>
<h2 id="heading-what-does-the-m-flag-do">What Does the "m" Flag Do?</h2>
<p>Sometimes, you want your matches not to occur only in a single line but also reach other lines below the first one. This is when the multiline flag is influential. </p>
<p>Almost all the popular regex engines out there have a way you can toggle on and off the multiline flag.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-26-at-12.48.37.png" alt="Image" width="600" height="400" loading="lazy">
<em>RegEx 101</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-26-at-12.49.25.png" alt="Image" width="600" height="400" loading="lazy">
<em>RegExr</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-26-at-12.48.50.png" alt="Image" width="600" height="400" loading="lazy">
<em>RegEx Tester from Dan's Tools</em></p>
<h2 id="heading-how-to-use-the-m-flag-in-regex-engines">How to Use the "m" Flag in RegEx Engines</h2>
<p>If you want your matches not to be limited to the first line while using a regex engine, all you need to do is toggle on the "m" flag.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-26-at-13.04.45.png" alt="Screenshot-2023-04-26-at-13.04.45" width="600" height="400" loading="lazy"></p>
<p>I have the multiline flag turned on and it’s not matching all the lines. Why that?</p>
<p>That’s because many times, you also have to use the global ["g"] flag with the "m" flag so you can get all the matches:
<img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-26-at-13.06.23.png" alt="Screenshot-2023-04-26-at-13.06.23" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-use-the-m-flag-in-javascript-regular-expressions">How to Use the "m" Flag in JavaScript Regular Expressions</h2>
<p>Remember that to use the regular expressions flag in JavaScript, you have to specify it as the second argument of a <code>RegExp()</code> constructor. And if you are creating your Regex with slashes, the flags have to be outside of the slashes.</p>
<pre><code class="lang-js"><span class="hljs-comment">// a flag is the second argument of a RegExp constructor</span>
<span class="hljs-keyword">const</span> regex1 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(<span class="hljs-string">'line'</span>, <span class="hljs-string">'gm'</span>);

<span class="hljs-comment">// a flag is the letter outside when you create regex with two forward slashes</span>
<span class="hljs-keyword">const</span> regex2 = <span class="hljs-regexp">/line/gm</span>;
</code></pre>
<p>Here’s how I use the "m" in conjunction with the "g" flag to match multiple lines in JavaScript:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> regex2 = <span class="hljs-regexp">/line/gim</span>;

<span class="hljs-keyword">const</span> multiLineStr = <span class="hljs-string">`Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7`</span>;

<span class="hljs-built_in">console</span>.log(regex2.test(multiLineStr)); <span class="hljs-comment">// true</span>

<span class="hljs-keyword">if</span> (regex2.test(multiLineStr)) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'There are multiple matches'</span>); <span class="hljs-comment">// There are multiple matches</span>
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Found no match'</span>);
}
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>You can now see how useful the multiline flag is in getting matches across all lines of text. </p>
<p>If you found the article helpful, don’t hesitate to share it with your friends and family.</p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Write Regular Expressions in a JSON File ]]>
                </title>
                <description>
                    <![CDATA[ JSON stands for JavaScript Object Notation. It is a text-based and lightweight data format for exchanging information between systems, for example, a web server and a web application. JSON files typically contain objects, arrays, strings, and numbers... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-write-regular-expression-in-json-file/</link>
                <guid isPermaLink="false">66adf155db5636c0b30cba7f</guid>
                
                    <category>
                        <![CDATA[ json ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Regex ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Mon, 24 Apr 2023 12:38:59 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/start-graph--11-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>JSON stands for JavaScript Object Notation. It is a text-based and lightweight data format for exchanging information between systems, for example, a web server and a web application.</p>
<p>JSON files typically contain objects, arrays, strings, and numbers. But you can also have regular expressions in a JSON file. And that’s what we are going to take a look at in this article.</p>
<h2 id="heading-how-to-write-regex-inside-json">How to Write RegEx inside JSON</h2>
<p>Remember each entry in a JSON file is a <code>key:value</code> pair surrounded by double quotes. So, if you want to write RegEx inside your JSON file, you need to specify the key and the value and surrounded both with double quotes. </p>
<p>The key can just be an arbitrary name, and the value would be the regex itself. Here’s an example of a JSON file with regular expressions:</p>
<pre><code class="lang-js"><span class="hljs-comment">// data.json file</span>

{
  <span class="hljs-string">"nigeriaPhone"</span>: <span class="hljs-string">"^(\\+?234|0)[789]\\d{9}$"</span>,
  <span class="hljs-string">"email"</span>: <span class="hljs-string">"^([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5})$"</span>,
  <span class="hljs-string">"password"</span>: <span class="hljs-string">"^(?=.*[0-9])(?=.*[!@#\\$%^&amp;*])[a-zA-Z0-9!@#\\$%^&amp;*]{8,}$"</span>,
  <span class="hljs-string">"url"</span>: <span class="hljs-string">"^(http|https)://[a-zA-Z0-9-\\.]+\\.[a-zA-Z]{2,5}(/[a-zA-Z0-9-._~:/?#[\\]@!$&amp;'()*+,;=]*)?$"</span>
}
</code></pre>
<p>Writing RegEx inside a JSON file can be useful when you want to use many regular expressions. </p>
<p>Instead of littering your JavaScript, Python file, or any other programming files with regular expressions, you can put all of them inside a JSON file. You can then import the file into your programming language file and use the regular expressions entries.</p>
<p>That takes us to how to use a JSON file inside a programming language. Specifically, we’ll look at how to do that in JavaScript.</p>
<h2 id="heading-how-to-use-a-json-regex-in-a-javascript-file">How to use a JSON RegEx in a JavaScript File</h2>
<p>To use the RegEx from your JSON file inside a JavaScript file, you need to import it first. </p>
<p>An ordinary <code>import something from somefile</code> won't work if you want to import JSON into a JS file. This is the correct way to do it:</p>
<pre><code class="lang-bash">import someName from <span class="hljs-string">'location/file.json'</span> assert { <span class="hljs-built_in">type</span>: <span class="hljs-string">'json'</span> };
</code></pre>
<p>So, I'm going to import the JSON file like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> validators <span class="hljs-keyword">from</span> <span class="hljs-string">'./data.json'</span> assert { <span class="hljs-attr">type</span>: <span class="hljs-string">'json'</span> };
</code></pre>
<p>In this case, I’m importing all the entries from the <code>data.json</code> file and naming them <code>validators</code>. This name can be anything. </p>
<p>The <code>assert { type:  'json'}</code> part ensures that what I’m bringing in is a JSON object.</p>
<p>You can then chain any of the keys from the JSON file to <code>validators</code> to see what any of the entries look like:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> validators <span class="hljs-keyword">from</span> <span class="hljs-string">'./data.json'</span> assert { <span class="hljs-attr">type</span>: <span class="hljs-string">'json'</span> };

<span class="hljs-built_in">console</span>.log(validators.nigeriaPhone); <span class="hljs-comment">// ^(\+?234|0)[789]\d{9}$</span>
<span class="hljs-built_in">console</span>.log(validators.email); <span class="hljs-comment">// ^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$</span>
<span class="hljs-built_in">console</span>.log(validators.password); <span class="hljs-comment">// ^(?=.*[0-9])(?=.*[!@#\$%^&amp;*])[a-zA-Z0-9!@#\$%^&amp;*]{8,}$</span>
<span class="hljs-built_in">console</span>.log(validators.url); <span class="hljs-comment">// ^(http|https)://[a-zA-Z0-9-\.]+\.[a-zA-Z]{2,5}(/[a-zA-Z0-9-._~:/?#[\]@!$&amp;'()*+,;=]*)?$</span>
</code></pre>
<p>You can even take this further and test what the regular expressions validate. Here’s how I validated a correct Nigerian phone number:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> validators <span class="hljs-keyword">from</span> <span class="hljs-string">'./data.json'</span> assert { <span class="hljs-attr">type</span>: <span class="hljs-string">'json'</span> };

<span class="hljs-keyword">const</span> naijaNUmber = <span class="hljs-string">'+2348123456789'</span>;

<span class="hljs-keyword">if</span> (naijaNUmber.match(validators.nigeriaPhone)) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"That's a valid Naija phone number"</span>); <span class="hljs-comment">// That's a valid Naija phone number</span>
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"That's not a valid Naija phone number"</span>);
}
</code></pre>
<p>And here’s how I used the <code>password</code> key to validate a password that is at least eight characters long and contains at least one number and at least one special character:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> validators <span class="hljs-keyword">from</span> <span class="hljs-string">'./data.json'</span> assert { <span class="hljs-attr">type</span>: <span class="hljs-string">'json'</span> };

<span class="hljs-keyword">const</span> pword = <span class="hljs-string">'JohnDoe'</span>;

<span class="hljs-keyword">if</span> (pword.match(validators.password)) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"That's Valid password"</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(
    <span class="hljs-string">'Your password must be 8 characters long with at least 1 number and 1 special character'</span>
  ); <span class="hljs-comment">// Your password must be 8 characters long with at least 1 number and 1 special character</span>
}
</code></pre>
<p>Unfortunately, in some situations, you get an error if you decide to use the JSON regex directly without creating a regex out of it. Here’s an example with <code>test()</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> validators <span class="hljs-keyword">from</span> <span class="hljs-string">'./data.json'</span> assert { <span class="hljs-attr">type</span>: <span class="hljs-string">'json'</span> };

<span class="hljs-keyword">const</span> naijaPhone = validators.nigeriaPhone;
<span class="hljs-built_in">console</span>.log(naijaPhone); <span class="hljs-comment">// Output: ^(\+?234|0)[789]\d{9}$</span>

<span class="hljs-built_in">console</span>.log(naijaPhone.test(<span class="hljs-number">83412343433</span>));

<span class="hljs-comment">/* output: dex.js:4 Uncaught TypeError: naijaPhone.test is not a function
    at index.js:4:24
*/</span>
</code></pre>
<p>You can see that the output does not show it as a regular expression – it is not surrounded by forward slashes. This means you have to create a regex out of it with the regex constructor:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> validators <span class="hljs-keyword">from</span> <span class="hljs-string">'./data.json'</span> assert { <span class="hljs-attr">type</span>: <span class="hljs-string">'json'</span> };

<span class="hljs-keyword">const</span> naijaPhone = validators.nigeriaPhone;
<span class="hljs-built_in">console</span>.log(naijaPhone); <span class="hljs-comment">// Output: ^(\+?234|0)[789]\d{9}$</span>

<span class="hljs-comment">// Create a regex out of validators.nigeriaPhone;</span>
<span class="hljs-keyword">const</span> naijaNumberRegex = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(naijaPhone);
<span class="hljs-built_in">console</span>.log(naijaNumberRegex); <span class="hljs-comment">// Output: /^(\+?234|0)[789]\d{9}$/</span>
</code></pre>
<p>You can see it is now surrounded by forward slashes – that’s a way to identify and even create regex in JavaScript.</p>
<p>Here's how the chrome developer tools distinguishes the two:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-24-at-12.22.56.png" alt="Screenshot-2023-04-24-at-12.22.56" width="600" height="400" loading="lazy"></p>
<p>It is with that regex you created that you can test the number:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> validators <span class="hljs-keyword">from</span> <span class="hljs-string">'./data.json'</span> assert { <span class="hljs-attr">type</span>: <span class="hljs-string">'json'</span> };

<span class="hljs-keyword">const</span> naijaPhone = validators.nigeriaPhone;
<span class="hljs-built_in">console</span>.log(naijaPhone); <span class="hljs-comment">// Output: ^(\+?234|0)[789]\d{9}$</span>

<span class="hljs-comment">// Create a regex out of validators.nigeriaPhone;</span>
<span class="hljs-keyword">const</span> naijaNumberRegex = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(naijaPhone);
<span class="hljs-built_in">console</span>.log(naijaNumberRegex); <span class="hljs-comment">// Output: /^(\+?234|0)[789]\d{9}$/</span>

<span class="hljs-comment">// test it out with the regex</span>
<span class="hljs-built_in">console</span>.log(naijaNumberRegex.test(<span class="hljs-number">83412343433</span>)); <span class="hljs-comment">// output: false</span>
<span class="hljs-built_in">console</span>.log(naijaNumberRegex.test(<span class="hljs-number">2348033333333</span>)); <span class="hljs-comment">// output: true</span>
</code></pre>
<p>The reason why it worked with the <code>match()</code> method and didn’t work with <code>test()</code> is this:</p>
<ul>
<li><p>when you use the <code>match()</code> method, you can directly pass the regular expression string that you read from a JSON file as an argument to the method, and JavaScript will automatically create a regular expression from the string.</p>
</li>
<li><p>when you use the <code>test()</code> method, you need to manually create a regular expression from the regular expression string using the <code>new RegExp()</code> constructor. This is because the <code>test()</code> method expects a regular expression object as its argument, not a string.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>You’ve seen that there’s no extra caveat involved in writing regular expressions in a JSON file – you still have to follow the same rules for writing JSON.</p>
<p>And when you import that JSON file into a JavaScript file, you don’t need to do anything extra to make it work, other than creating a regex out of it with the <code>new RegExp()</code> constructor in some cases.</p>
<p>Thank you for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What Does the Caret Mean in RegEx? Caret Metacharacter in Regular Expressions ]]>
                </title>
                <description>
                    <![CDATA[ A caret (^) is one of the many symbols for creating patterns in regular expressions.  A caret matches the start of a line or a particular string. But that’s not all there is to the caret (^) symbol. The caret symbol (^) is often referred to as an "an... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-does-the-caret-mean-in-regex-how-to-match-the-start-of-a-line-in-regular-expressions/</link>
                <guid isPermaLink="false">66adf25a11a28b6eb378d2d1</guid>
                
                    <category>
                        <![CDATA[ Regex ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Thu, 20 Apr 2023 16:47:22 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/caretMeta.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A caret (<code>^</code>) is one of the many symbols for creating patterns in regular expressions. </p>
<p>A caret matches the start of a line or a particular string. But that’s not all there is to the caret (<code>^</code>) symbol.</p>
<p>The caret symbol (<code>^</code>) is often referred to as an "anchor" because it anchors the pattern to the beginning of a line or string.  So, you can call it "start of line anchor". </p>
<p>The other anchor is the dollar sign (<code>$</code>), which anchors the pattern to the end of the line, which means it is "end of line anchor".</p>
<h2 id="heading-what-well-cover">What We'll Cover</h2>
<ul>
<li><a class="post-section-overview" href="#heading-what-does-the-caret-symbol-do-in-regex">What Does the Caret Symbol Do in RegEx</a></li>
<li><a class="post-section-overview" href="#heading-how-to-match-the-start-of-a-line-with-caret">How to Match the Start of a Line with Caret</a></li>
<li><a class="post-section-overview" href="#heading-how-to-negate-a-character-set-with-caret">How to Negate a Character Set with Caret</a></li>
<li><a class="post-section-overview" href="#heading-how-to-match-the-caret-as-a-character-in-a-string">How to Match the Caret as a Character in a String</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-caret-metacharacter-in-javascript">How to Use the Caret Metacharacter in JavaScript</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-what-does-the-caret-symbol-do-in-regex">What Does the Caret Symbol Do in RegEx?</h2>
<p>There are two main things the caret symbol does – it matches the start of a line or the start of a string, and it negates a character set when you put it inside the square brackets.</p>
<p>In addition, you might want to match the caret symbol itself since it's used for other things outside of regular expressions. In that case, you have to escape it.</p>
<h2 id="heading-how-to-match-the-start-of-a-line-with-caret">How to Match the Start of a Line with Caret</h2>
<p>To match the start of a line with the caret symbol, prepend your pattern with it.</p>
<p>In the example below, I have the pattern <code>/^hello\s*world/igm</code> which would only match a <code>hello world</code> text that is at the start of a line. Any other <code>hello world</code> in between or at the end of a line won’t be a match:
<img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-20-at-14.21.33.png" alt="Screenshot-2023-04-20-at-14.21.33" width="600" height="400" loading="lazy"></p>
<p>Also, the pattern <code>/^c/igm</code> would only match the words that start with the letter <code>c</code> only if they are at the start of the line:
<img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-20-at-14.22.33.png" alt="Screenshot-2023-04-20-at-14.22.33" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-negate-a-character-set-with-caret">How to Negate a Character Set with Caret</h2>
<p>Another thing you can do with the caret is to negate a character set. For example, if you want to negate vowels, you can put them in a character set and prepend caret to them:
<img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-20-at-14.29.46.png" alt="Screenshot-2023-04-20-at-14.29.46" width="600" height="400" loading="lazy"></p>
<p>You can see that all the vowels were not matched.</p>
<h2 id="heading-how-to-match-the-caret-as-a-character-in-a-string">How to Match the Caret as a Character in a String</h2>
<p>You can use caret for other things like exponentiation in Mathematics and bitwise XOR operator in C++. </p>
<p>If you want to match it, you have to escape it with a backslash <code>\</code> since its recognized as a metacharacter by RegEx engines:
<img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-20-at-14.39.07.png" alt="Screenshot-2023-04-20-at-14.39.07" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-use-the-caret-metacharacter-in-javascript">How to Use the Caret Metacharacter in JavaScript</h2>
<p>The caret metacharacter works fine in JavaScript. The code snippet below shows I test it with some strings:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> text1 = <span class="hljs-string">`There's hello world in every programming language
Hello world is what starts many programming language courses.
Many programmers don't know any other hello apart from hello world.`</span>;

<span class="hljs-keyword">const</span> text2 = <span class="hljs-string">`caret is anchors your pattern to the start of a line
To match the caret itself, you have to escape it.`</span>;

<span class="hljs-keyword">const</span> text3 = <span class="hljs-string">'4 raised to power 2 in mathematics is 4 ^ 2'</span>;

<span class="hljs-keyword">const</span> re1 = <span class="hljs-regexp">/^hello\s*world/gim</span>;
<span class="hljs-keyword">const</span> re2 = <span class="hljs-regexp">/^c/gim</span>;
<span class="hljs-keyword">const</span> re3 = <span class="hljs-regexp">/\^/</span>;

<span class="hljs-built_in">console</span>.log(re1.test(text1)); <span class="hljs-comment">//true</span>
<span class="hljs-built_in">console</span>.log(re2.test(text2)); <span class="hljs-comment">//true</span>
<span class="hljs-built_in">console</span>.log(re3.test(text3)); <span class="hljs-comment">//true</span>
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This article showed you how you can use the "start of line anchor" (caret <code>^</code> metacharacter) to anchor a pattern to the start of a line or string in both RegEx engines and JavaScript.</p>
<p>To learn about the end of line anchor (<code>$</code>), you can read <a target="_blank" href="https://www.freecodecamp.org/news/what-does-mean-in-regex/">this article</a>.</p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What Does $ Mean in RegEx? Dollar Metacharacter in Regular Expressions ]]>
                </title>
                <description>
                    <![CDATA[ The $ symbol is one of the most commonly used symbols in RegEx. It is used to match the end of a string. In other words, you can call it "end of line anchor", since it anchors a pattern to the end of the line. In this article, I’ll show ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-does-mean-in-regex/</link>
                <guid isPermaLink="false">66adf2537550d4f37c2019d5</guid>
                
                    <category>
                        <![CDATA[ Regex ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Wed, 19 Apr 2023 11:20:42 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/start-graph--10-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The <code>$</code> symbol is one of the most commonly used symbols in RegEx. It is used to match the end of a string. In other words, you can call it "end of line anchor", since it anchors a pattern to the end of the line.</p>
<p>In this article, I’ll show you exactly what the dollar sign (<code>$</code>) does in RegEx and how to use it.</p>
<h2 id="heading-what-well-cover">What We'll Cover</h2>
<ul>
<li><a class="post-section-overview" href="#heading-what-is-the-symbol-in-regex">What is the <code>$</code> Symbol in RegEx?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-match-the-dollar-sign-in-regex">How to Match the Dollar Sign <code>$</code> in RegEx</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-dollar-sign-in-a-javascript-regex">How to Use the Dollar Sign <code>$</code> in a JavaScript Regex</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-what-is-the-symbol-in-regex">What is the <code>$</code> Symbol in RegEx?</h2>
<p>The <code>$</code> is one of the RegEx characters known as metacharacters. It matches the end of a string and would only return a match when the text or string it is attached to is at the end of a line.</p>
<p>This is useful in cases where you want to ensure that a string ends with a certain pattern or character. You can use the <code>$</code> metacharacter with other metacharacters to create complex patterns that match specific strings or patterns within strings.</p>
<p>In the example below, you can see that the pattern is <code>freecodecamp$</code> with the <code>i</code>, <code>g</code>, and <code>m</code> flags. <code>i</code> means case insensitive, <code>g</code> means global, and <code>m</code> means multiline.
<img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-19-at-10.46.29.png" alt="Screenshot-2023-04-19-at-10.46.29" width="600" height="400" loading="lazy"></p>
<p>You can also see that only the word <code>freeCoceCamp</code> at the end of a line is returned as matches. That’s the power of the <code>$</code> metacharacter.</p>
<h2 id="heading-how-to-match-the-dollar-sign-in-regex">How to Match the Dollar Sign <code>$</code> in RegEx</h2>
<p>Since the dollar sign <code>$</code> is a metacharacter, how would you match it in a string? You have to escape it with a backslash! That’s how you match all metacharacters in RegEx.
<img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-19-at-10.46.37.png" alt="Screenshot-2023-04-19-at-10.46.37" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-use-the-dollar-sign-in-a-javascript-regex">How to Use the Dollar Sign <code>$</code> in a JavaScript Regex</h2>
<p>The dollar sign <code>$</code> metacharacter works fine in JavaScript. In the code snippet below, I test the dollar sign as a metacharacter and as a string:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> text1 =
  <span class="hljs-string">"At freeCodeCamp, we don't ask you to pay to learn coding, because freeCodeCamp is a charity"</span>;

<span class="hljs-keyword">const</span> text2 =
  <span class="hljs-string">'You can also hang out with friends on a forum developed by freeCodeCamp'</span>;

<span class="hljs-keyword">const</span> text3 = <span class="hljs-string">'The sign of the naira is ₦ and dollar sign is $.'</span>;

<span class="hljs-keyword">const</span> regex1 = <span class="hljs-regexp">/freecodecamp$/gim</span>;
<span class="hljs-keyword">const</span> regex2 = <span class="hljs-regexp">/\$/g</span>;

<span class="hljs-comment">// test the dollar sign as a metacharacter</span>
<span class="hljs-built_in">console</span>.log(regex1.test(text1)); <span class="hljs-comment">//false</span>
<span class="hljs-built_in">console</span>.log(regex2.test(text2)); <span class="hljs-comment">//true</span>

<span class="hljs-comment">// test the dollar sign as a string</span>
<span class="hljs-built_in">console</span>.log(regex2.test(text3)); <span class="hljs-comment">//true</span>
</code></pre>
<p>You can see that when I tested the string <code>At freeCodeCamp, we don't ask you to pay to learn coding, because freeCodeCamp is a charity</code> with the regex <code>/freecodecamp$/gim;</code>, it returned <code>false</code> because there’s no <code>freeCodeCamp</code> at the end of a line. But when I tested <code>You can also hang out with friends on a forum developed by freeCodeCamp'</code> with the same regex, it returned <code>true</code> because there’s a <code>freeCodeCamp</code> at the end of a line.</p>
<p>Also, you can see that the string <code>'The sign of the naira is ₦ and dollar sign is $.'</code> returned <code>true</code> when I tested it with the regex <code>/\$/g</code>.</p>
<p>You can also use the <code>exec()</code> method instead of <code>test()</code> to see the exact matches of your regex:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> text1 =
  <span class="hljs-string">"At freeCodeCamp, we don't ask you to pay to learn coding, because freeCodeCamp is a charity"</span>;

<span class="hljs-keyword">const</span> text2 =
  <span class="hljs-string">'You can also hang out with friends on a forum developed by freeCodeCamp'</span>;

<span class="hljs-keyword">const</span> text3 = <span class="hljs-string">'The sign of the naira is ₦ and dollar sign is $.'</span>;

<span class="hljs-keyword">const</span> regex1 = <span class="hljs-regexp">/freecodecamp$/gim</span>;
<span class="hljs-keyword">const</span> regex2 = <span class="hljs-regexp">/\$/g</span>;

<span class="hljs-comment">// test the dollar sign as a metacharacter</span>
<span class="hljs-built_in">console</span>.log(regex1.exec(text1));
<span class="hljs-built_in">console</span>.log(regex1.exec(text2));

<span class="hljs-comment">// test the dollar sign as a string</span>
<span class="hljs-built_in">console</span>.log(regex2.exec(text3));
</code></pre>
<p>Output:</p>
<pre><code class="lang-js"><span class="hljs-literal">null</span>
[
  <span class="hljs-string">'freeCodeCamp'</span>,
  <span class="hljs-attr">index</span>: <span class="hljs-number">59</span>,
  <span class="hljs-attr">input</span>: <span class="hljs-string">'You can also hang out with friends on a forum developed by freeCodeCamp'</span>,
  <span class="hljs-attr">groups</span>: <span class="hljs-literal">undefined</span>
]
[
  <span class="hljs-string">'$'</span>,
  <span class="hljs-attr">index</span>: <span class="hljs-number">46</span>,
  <span class="hljs-attr">input</span>: <span class="hljs-string">'The sign of the naira is ₦ and dollar sign is $.'</span>,
  <span class="hljs-attr">groups</span>: <span class="hljs-literal">undefined</span>
]
</code></pre>
<p>The first console log returned <code>null</code> because there was no match. The second returned the match, and the third returned the match too.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>You’ve seen how the dollar (<code>$</code>) metacharacter matches the end of a line in RegEx and in JavaScript.</p>
<p>You can combine the dollar metacharacter with several other metacharacters to create a complex pattern. For instance, since caret (<code>^</code>) matches the start of a line, you can combine it with the dollar metacharacter to match a particular word only.</p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Include an Empty String in RegEx ]]>
                </title>
                <description>
                    <![CDATA[ Regular expressions (RegEx or RegExp for short) are a sequence of characters that define a search pattern.  You can use them to search, replace, and validate the strings of a text in a wide variety of applications, such as text editors, developer too... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-include-empty-string-in-regex/</link>
                <guid isPermaLink="false">66adf12c6f5e63db3fc43615</guid>
                
                    <category>
                        <![CDATA[ Regex ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Fri, 31 Mar 2023 11:50:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/start-graph--7-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Regular expressions (RegEx or RegExp for short) are a sequence of characters that define a search pattern. </p>
<p>You can use them to search, replace, and validate the strings of a text in a wide variety of applications, such as text editors, developer tools, and command line tools.</p>
<p>RegEx is also widely used in programming languages because many of the languages have built-in support for it.</p>
<p>Since you can match the strings of a text with RegEx, it means you can also match empty strings. </p>
<p>In this article, I’ll show you three ways to match an empty string in RegEx.</p>
<h2 id="heading-what-well-cover">What We'll Cover</h2>
<ul>
<li><a class="post-section-overview" href="#heading-how-to-match-empty-string-in-regex-with-the-caret-and-dollar-sign-metacharacters">How to Match Empty String in RegEx with the Caret and Dollar Sign Metacharacters</a></li>
<li><a class="post-section-overview" href="#heading-how-to-match-empty-string-in-regex-with-a-lookahead">How to Match Empty String in RegEx with a Lookahead</a></li>
<li><a class="post-section-overview" href="#heading-how-to-match-empty-string-in-regex-with-a-negative-lookahead">How to Match Empty String in RegEx with a Negative Lookahead</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-how-to-match-empty-string-in-regex-with-the-caret-and-dollar-sign-metacharacters">How to Match Empty String in RegEx with the Caret and Dollar Sign Metacharacters</h2>
<p>The caret (<code>^</code>) and dollar sign (<code>$</code>) metacharacters match the start of a string and its end, respectively.
<img src="https://www.freecodecamp.org/news/content/images/2023/03/Screenshot-2023-03-31-at-08.22.21.png" alt="Screenshot-2023-03-31-at-08.22.21" width="600" height="400" loading="lazy"></p>
<p>So, if you don’t put anything between both <code>^</code> and <code>$</code>, it matches an empty string:</p>
<pre><code class="lang-console">^$
</code></pre>
<h2 id="heading-how-to-match-empty-string-in-regex-with-a-lookahead">How to Match Empty String in RegEx with a Lookahead</h2>
<p>In RegEx, a lookahead is a zero-width assertion that allows you to match a string only if it is followed by another specific string without including that specific string in the match result. </p>
<p>There are both positive and negative lookaheads in RegEx. <code>?=</code> indicates a positive lookahead and <code>?!</code> indicates a negative lookahead. You can use them to create more complex regular expressions.</p>
<p>Let’s look at how to match an empty string with a positive lookahead:</p>
<pre><code class="lang-console">^(?=\s*$)
</code></pre>
<p>In the pattern above:</p>
<ul>
<li>the <code>^</code> character matches the beginning of the string</li>
<li>the <code>(?=\s*$)</code> is a positive lookahead that matches a position in the string where the following is true:</li>
<li><code>\s*</code> matches zero or more whitespace characters</li>
<li><code>$</code> matches the end of the string</li>
</ul>
<p>Since the lookahead only matches the position and not any characters, the regular expression will match only an empty string.</p>
<h2 id="heading-how-to-match-empty-string-in-regex-with-a-negative-lookahead">How to Match Empty String in RegEx with a Negative Lookahead</h2>
<p>As I mentioned earlier, <code>?!</code> specifies a negative lookahead. You can use the negative lookahead below to match an empty string:</p>
<pre><code class="lang-console">^(?!.*\S)
</code></pre>
<p>In the RegEx above:</p>
<ul>
<li>the <code>^</code> character matches the beginning of the string</li>
<li>the <code>(?!.*\S)</code> is a negative lookahead that matches a position in the string where the following is not true:</li>
<li><code>.*</code> matches zero or more characters</li>
<li><code>\S</code> matches any non-whitespace character</li>
</ul>
<p>Since the negative lookahead only matches the position and not any characters, the regular expression will match an empty string.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In many RegEx testing engines, you won’t get a match for an empty string if you test an empty string with start and end metacharacters, negative lookahead, and positive lookahead.
<img src="https://www.freecodecamp.org/news/content/images/2023/03/Screenshot-2023-03-31-at-09.19.48.png" alt="Screenshot-2023-03-31-at-09.19.48" width="600" height="400" loading="lazy"></p>
<p>But in JavaScript, for example, you’ll get a match:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Start and end metacharacters</span>
<span class="hljs-keyword">const</span> regEx1 = <span class="hljs-regexp">/^$/g</span>;

<span class="hljs-comment">// Positive lookahead</span>
<span class="hljs-keyword">const</span> regEx2 = <span class="hljs-regexp">/^(?=\s*$)/g</span>;

<span class="hljs-comment">// Negative lookahead</span>
<span class="hljs-keyword">const</span> regEx3 = <span class="hljs-regexp">/^(?!.*\S)/g</span>;

<span class="hljs-keyword">const</span> text = <span class="hljs-string">''</span>;

<span class="hljs-built_in">console</span>.log(regEx1.exec(text)); <span class="hljs-comment">// [ '', index: 0, input: '', groups: undefined ]</span>
<span class="hljs-built_in">console</span>.log(regEx2.exec(text)); <span class="hljs-comment">// [ '', index: 0, input: '', groups: undefined ]</span>
<span class="hljs-built_in">console</span>.log(regEx3.exec(text)); <span class="hljs-comment">// [ '', index: 0, input: '', groups: undefined ]</span>

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'\n'</span>);

<span class="hljs-built_in">console</span>.log(regEx1.test(text)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(regEx2.test(text)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(regEx3.test(text)); <span class="hljs-comment">// true</span>
</code></pre>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Regular Expressions in CTRL F ]]>
                </title>
                <description>
                    <![CDATA[ The conventional CTRL + F does not support Regex in many software tools we use in our day-to-day lives. But almost nothing is impossible in the tech world. Many of these software tools, such as VS Code, Chrome browser, Dreamweaver, Jetbrains, and oth... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-do-you-use-regular-expression-in-ctrl-f/</link>
                <guid isPermaLink="false">66adf0f2b0efb2bf012fd7c5</guid>
                
                    <category>
                        <![CDATA[ Regex ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Thu, 30 Mar 2023 13:12:06 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/start-graph--6-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The conventional <code>CTRL + F</code> does not support Regex in many software tools we use in our day-to-day lives. But almost nothing is impossible in the tech world.</p>
<p>Many of these software tools, such as VS Code, Chrome browser, Dreamweaver, Jetbrains, and others, have a built-in mechanism that supports RegEx while using <code>CTRL + F</code> to search a page or document.</p>
<p>Let’s look at how you can search with <code>CTRL + F</code> using RegEx in VS Code, Chrome browser, and Chrome developer tools.</p>
<h2 id="heading-what-well-cover">What We'll Cover</h2>
<ul>
<li><a class="post-section-overview" href="#heading-how-to-use-regular-expressions-in-ctrl-f-inside-vs-code">How to Use Regular Expressions in <code>CTRL + F</code> Inside VS Code</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-regular-expressions-in-ctrl-f-in-chrome-developer-tools">How to Use Regular Expressions in <code>CTRL + F</code> in Chrome Developer Tools</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-regular-expressions-in-ctrl-f-on-a-chrome-webpage">How to Use Regular Expressions in <code>CTRL + F</code> on a Chrome Webpage</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-how-to-use-regular-expressions-in-ctrl-f-inside-vs-code">How to Use Regular Expressions in <code>CTRL + F</code> Inside VS Code</h2>
<p>Press <code>CTRL + F</code> and the search interface will appear:
<img src="https://www.freecodecamp.org/news/content/images/2023/03/Screenshot-2023-03-30-at-11.09.19.png" alt="Screenshot-2023-03-30-at-11.09.19" width="600" height="400" loading="lazy"></p>
<p>Hover on <code>.*</code> and “Use Regular Expression” with some keyboard combinations should appear:
<img src="https://www.freecodecamp.org/news/content/images/2023/03/Screenshot-2023-03-30-at-11.10.50.png" alt="Screenshot-2023-03-30-at-11.10.50" width="600" height="400" loading="lazy"></p>
<p>Anywhere you see the <code>.*</code> sign, it means RegEx. Click on it to start searching with RegEx.</p>
<p>Enter your RegEx and the search results show up:
<img src="https://www.freecodecamp.org/news/content/images/2023/03/Screenshot-2023-03-30-at-11.17.13.png" alt="Screenshot-2023-03-30-at-11.17.13" width="600" height="400" loading="lazy"></p>
<p>If the only thing you want to do with <code>CTRL + F</code> is to search using RegEx, the <code>ALT + CTRL + R</code> keyboard combination toggles <code>CTRL + F</code> search with RegEx on and off.</p>
<h2 id="heading-how-to-use-regular-expressions-in-ctrl-f-in-chrome-developer-tools">How to Use Regular Expressions in <code>CTRL + F</code> in Chrome Developer Tools</h2>
<p>You can also search using RegEx in the Chrome developer tools when you open a page source.</p>
<p>Right-click anywhere on a page and select “Inspect”:
<img src="https://www.freecodecamp.org/news/content/images/2023/03/Screenshot-2023-03-30-at-11.22.21.png" alt="Screenshot-2023-03-30-at-11.22.21" width="600" height="400" loading="lazy"></p>
<p>Click the 3 dots in the top right corner and select search to reveal the dev tools search interface:
<img src="https://www.freecodecamp.org/news/content/images/2023/03/Screenshot-2023-03-30-at-11.23.01.png" alt="Screenshot-2023-03-30-at-11.23.01" width="600" height="400" loading="lazy"></p>
<p>You can also press <code>CTRL + ALT + F</code> on Windows or <code>CMD + ALT + F</code> on Mac to do this.</p>
<p>Click on the <code>.*</code> button to search with RegEx:
<img src="https://www.freecodecamp.org/news/content/images/2023/03/Screenshot-2023-03-30-at-11.24.59.png" alt="Screenshot-2023-03-30-at-11.24.59" width="600" height="400" loading="lazy"></p>
<p>Type in your RegEx and press <code>ENTER</code> to reveal the search results:
<img src="https://www.freecodecamp.org/news/content/images/2023/03/Screenshot-2023-03-30-at-11.27.20.png" alt="Screenshot-2023-03-30-at-11.27.20" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-use-regular-expressions-in-ctrl-f-on-a-chrome-webpage">How to Use Regular Expressions in <code>CTRL + F</code> on a Chrome Webpage</h2>
<p>Since you can search with RegEx in the Chrome developer tools, you might be wondering how to search with RegEx on a web page. </p>
<p>Although Chrome does not have this functionality built into it, you can install an extension to let you do so.</p>
<p>Head over to <a target="_blank" href="https://chrome.google.com/webstore/category/extensions">Chrome Web Store</a> and search for RegEx:
<img src="https://www.freecodecamp.org/news/content/images/2023/03/Screenshot-2023-03-30-at-11.33.27.png" alt="Screenshot-2023-03-30-at-11.33.27" width="600" height="400" loading="lazy"></p>
<p>Install the Chrome RegEx search extension:
<img src="https://www.freecodecamp.org/news/content/images/2023/03/Screenshot-2023-03-30-at-11.34.10.png" alt="Screenshot-2023-03-30-at-11.34.10" width="600" height="400" loading="lazy"></p>
<p>Close and reopen your Chrome browser. Then head over to your extensions and select “Chrome Regex Search”:
<img src="https://www.freecodecamp.org/news/content/images/2023/03/Screenshot-2023-03-30-at-11.39.34.png" alt="Screenshot-2023-03-30-at-11.39.34" width="600" height="400" loading="lazy"></p>
<p>Enter your RegEx and the search results show up:
<img src="https://www.freecodecamp.org/news/content/images/2023/03/Screenshot-2023-03-30-at-11.38.35.png" alt="Screenshot-2023-03-30-at-11.38.35" width="600" height="400" loading="lazy"></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Even though a lot of software doesn’t come with a default <code>CTRL + F</code> search with RegEx, there is a way to either enable this functionality or install an extension.</p>
<p>VS Code and Google Chrome have this functionality built-in.</p>
<p>With Chrome developer tools, press <code>CTRL + SHIFT + F</code> on Windows and <code>CMD + SHIFT + F</code> on Mac, and then the same <code>.*</code> button to search with RegEx. You do the exact same in VS Code. </p>
<p>On a web page, Chrome doesn’t support searching with <code>CTRL + F</code> by using RegEx, but you can download extensions that add this functionality.</p>
<p>If you’re using any other tool and want to search using RegEx, a quick web search will point you in the right direction.</p>
<p>Thanks for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
