[Tut] Regex Special Characters – Examples in Python Re - Printable Version +- Sick Gaming (https://www.sickgaming.net) +-- Forum: Programming (https://www.sickgaming.net/forum-76.html) +--- Forum: Python (https://www.sickgaming.net/forum-83.html) +--- Thread: [Tut] Regex Special Characters – Examples in Python Re (/thread-93779.html) |
[Tut] Regex Special Characters – Examples in Python Re - xSicKxBot - 02-27-2020 Regex Special Characters – Examples in Python Re <div><p>Regular expressions are a strange animal. Many students find them difficult to understand – do you? </p> <figure class="wp-block-embed-youtube wp-block-embed is-type-rich is-provider-embed-handler wp-embed-aspect-16-9 wp-has-aspect-ratio"> <div class="wp-block-embed__wrapper"> <div class="ast-oembed-container"><iframe title="Regex Special Characters - Examples in Python Re" width="1100" height="619" src="https://www.youtube.com/embed/hSy0xea-8p8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div> </p></div> </figure> <p>I realized that a major reason for this is simply that they don’t understand the special regex characters. To put it differently: understand the special characters and everything else in the regex space will come much easier to you.</p> <p><a href="https://blog.finxter.com/python-regex/" target="_blank" rel="noreferrer noopener" aria-label="Regular expressions (opens in a new tab)">Regular expressions</a> are built from characters. There are <a href="https://www.regular-expressions.info/characters.html" target="_blank" rel="noreferrer noopener" aria-label=" (opens in a new tab)">two types</a> of characters: <strong>literal characters</strong> and <strong>special characters</strong>.</p> <h2>Literal Characters</h2> <p>Let’s start with the absolute first thing you need to know with regular expressions: a regular expression (short: <em>regex</em>) searches for a given pattern in a given string.</p> <p>What’s a pattern? In its most basic form, a pattern can be a literal character. So the literal characters <code>'a'</code>, <code>'b'</code>, and <code>'c'</code> are all valid regex patterns. </p> <p>For example, you can search for the regex pattern <code>'a'</code> in the string <code>'hello world'</code> but it won’t find a <em>match</em>. You can also search for the pattern <code>'a'</code> in the string <code>'hello woman'</code> and there is a match: the second last character in the string.</p> <p>Based on the simple insight that a literal character is a valid regex pattern, you’ll find that a combination of literal characters is also a valid regex pattern. For example, the regex pattern <code>'an'</code> matches the last two characters in the string <code>'hello woman'</code>. </p> <p><strong>Summary</strong>: Regular expressions are built from characters. An important class of characters are the literal characters. <a href="https://docs.python.org/3/library/re.html" target="_blank" rel="noreferrer noopener" aria-label="In principle (opens in a new tab)">In principle</a>, you can use all <a href="https://en.wikipedia.org/wiki/Unicode">Unicode</a> literal characters in your regex pattern. </p> <h2>Special Characters</h2> <p>However, the power of regular expressions come from their abstraction capability. Instead of writing the <a rel="noreferrer noopener" aria-label="character class (opens in a new tab)" href="https://blog.finxter.com/python-character-set-regex-tutorial/" target="_blank">character set</a> <code>[abcdefghijklmnopqrstuvwxyz]</code>, you’d write <code>[a-z]</code> or even <code>\w</code>. The latter is a special regex character—and pros know them by heart. In fact, regex experts seldomly match literal characters. In most cases, they use more advanced constructs or special characters for various reasons such as brevity, expressiveness, or generality. </p> <p><strong>So what are the special characters you can use in your regex patterns?</strong></p> <p>Let’s have a look at the following table that contains all special characters in Python’s <code>re</code> package for regular expression processing. </p> <figure class="wp-block-table is-style-stripes"> <table> <thead> <tr> <th>Special Character</th> <th>Meaning</th> </tr> </thead> <tbody> <tr> <td><code>\n</code></td> <td>The <strong>newline</strong> symbol is not a special symbol particular to regex only, it’s actually one of the most widely-used, standard characters. However, you’ll see the newline character so often that I just couldn’t write this list without including it. For example, the regex <code>'hello\nworld'</code> matches a string where the string <code>'hello'</code> is placed in one line and the string <code>'world'</code> is placed into the second line. </td> </tr> <tr> <td><code>\t</code></td> <td>The <strong>tabular</strong> character is, like the newline character, not a “regex-specific” symbol. It just encodes the tabular space <code>' '</code> which is different to a sequence of whitespaces (even if it doesn’t look different over here). For example, the regex <code>'hello\n\tworld'</code> matches the string that consists of <code>'hello'</code> in the first line and <code>' world'</code> in the second line (with a leading tab character).</td> </tr> <tr> <td><code>\s</code></td> <td>The <strong>whitespace</strong> character is, in contrast to the newline character, a special symbol of the regex libraries. You’ll find it in many other programming languages, too. The problem is that you often don’t know which type of whitespace is used: tabular characters, simple whitespaces, or even newlines. The whitespace character <code>'\s'</code> simply matches any of them. For example, the regex <code>'\s*hello\s+world'</code> matches the string <code>' \t \n hello \n \n \t world'</code>, as well as <code>'hello world'</code>.</td> </tr> <tr> <td><code>\S</code></td> <td>The <strong>whitespace-negation</strong> character matches everything that does not match <code>\s</code>. </td> </tr> <tr> <td><code>\w</code></td> <td>The <strong>word</strong> character regex simplifies text processing significantly. It represents the class of all characters used in typical words (<code>A-Z</code>, <code>a-z</code>, <code>0-9</code>, and <code>'_'</code>). This simplifies the writing of complex regular expressions significantly. For example, the regex <code>'\w+'</code> matches the strings <code>'hello'</code>, <code>'bye'</code>, <code>'Python'</code>, and <code>'Python_is_great'</code>. </td> </tr> <tr> <td><code>\W</code></td> <td>The <strong>word-character-negation</strong>. It matches any character that is not a word character.</td> </tr> <tr> <td><code>\b</code></td> <td>The <strong>word boundary</strong> is also a special symbol used in many regex tools. You can use it to match, as the name suggests, the boundary between the a word character (<code>\w</code>) and a non-word (<code>\W</code>) character. But note that it matches only the empty string! You may ask: why does it exist if it doesn’t match any character? The reason is that it doesn’t “consume” the character right in front or right after a word. This way, you can search for whole words (or parts of words) and return only the word but not the delimiting characters that separate the word, e.g., from other words.</td> </tr> <tr> <td><code>\d</code></td> <td>The <strong>digit character </strong>matches all numeric symbols between 0 and 9. You can use it to match integers with an arbitrary number of digits: the regex <code>'\d+'</code> matches integer numbers <code>'10'</code>, <code>'1000'</code>, <code>'942'</code>, and <code>'99999999999'</code>.</td> </tr> <tr> <td><code>\D</code></td> <td>Matches any <strong>non-digit character</strong>. This is the inverse of <code>\d</code> and it’s equivalent to <code>[^0-9]</code>. </td> </tr> </tbody> </table> </figure> <p>But these are not all characters you can use in a regular expression. </p> <p>There are also <em>meta characters</em> for the regex engine that allow you to do much more powerful stuff. </p> <p>A good example is the asterisk operator that matches “zero or more” occurrences of the preceding regex. For example, the pattern <code>.*txt</code> matches an arbitrary number of arbitrary characters followed by the suffix <code>'txt'</code>. This pattern has two special regex meta characters: the dot <code>.</code> and the asterisk operator <code>*</code>. You’ll now learn about those meta characters:</p> <h2>Regex Meta Characters</h2> <p>Feel free to watch the short video about the most important regex meta characters:</p> <figure class="wp-block-embed-youtube wp-block-embed is-type-rich is-provider-embed-handler wp-embed-aspect-4-3 wp-has-aspect-ratio"> <div class="wp-block-embed__wrapper"> <div class="ast-oembed-container"><iframe title="Python Regex Syntax [15-Minute Primer]" width="1100" height="825" src="https://www.youtube.com/embed/G1JLUpc-bvY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div> </p></div> </figure> <p>Next, you’ll get a quick and dirty overview of the most important regex operations and how to use them in Python.</p> <p>Here are the most important regex operators:</p> <figure class="wp-block-table is-style-stripes"> <table> <thead> <tr> <th>Meta Character</th> <th>Meaning</th> </tr> </thead> <tbody> <tr> <td><code>.</code></td> <td>The <strong>wild-card</strong> operator (<em>dot</em>) matches any character in a string except the newline character <code>'\n'</code>. For example, the regex <code>'...'</code> matches all words with three characters such as <code>'abc'</code>, <code>'cat'</code>, and <code>'dog'</code>. </td> </tr> <tr> <td><code>*</code></td> <td>The <strong>zero-or-more</strong> asterisk operator matches an arbitrary number of occurrences (including zero occurrences) of the immediately preceding regex. For example, the regex ‘cat*’ matches the strings <code>'ca'</code>, <code>'cat'</code>, <code>'catt'</code>, <code>'cattt'</code>, and <code>'catttttttt'</code>. </td> </tr> <tr> <td><code>?</code></td> <td>The <strong>zero-or-one</strong> operator matches (as the name suggests) either zero or one occurrences of the immediately preceding regex. For example, the regex ‘cat?’ matches both strings <code>‘ca’</code> and <code>‘cat’</code> — but not <code>‘catt’</code>, <code>‘cattt’</code>, and <code>‘catttttttt’</code>. </td> </tr> <tr> <td><code>+</code></td> <td>The <strong>at-least-one</strong> operator matches one or more occurrences of the immediately preceding regex. For example, the regex <code>‘cat+’</code> does not match the string <code>‘ca’</code> but matches all strings with at least one trailing character <code>‘t’</code> such as <code>‘cat’</code>, <code>‘catt’</code>, and <code>‘cattt’</code>. </td> </tr> <tr> <td><code>^</code></td> <td>The <strong>start-of-string</strong> operator matches the beginning of a string. For example, the regex <code>‘^p’</code> would match the strings <code>‘python’</code> and <code>‘programming’</code> but not <code>‘lisp’</code> and <code>‘spying’</code> where the character <code>‘p’</code> does not occur at the start of the string.</td> </tr> <tr> <td><code>$</code></td> <td>The <strong>end-of-string</strong> operator matches the end of a string. For example, the regex <code>‘py$’</code> would match the strings <code>‘main.py’</code> and <code>‘pypy’</code> but not the strings <code>‘python’</code> and <code>‘pypi’</code>. </td> </tr> <tr> <td><code>A|B</code></td> <td>The <strong>OR</strong> operator matches either the regex A or the regex B. Note that the intuition is quite different from the standard interpretation of the or operator that can also satisfy both conditions. For example, the regex <code>‘(hello)|(hi)’</code> matches strings <code>‘hello world’</code> and <code>‘hi python’</code>. It wouldn’t make sense to try to match both of them at the same time.</td> </tr> <tr> <td><code>AB</code> </td> <td>The <strong>AND</strong> operator matches first the regex A and second the regex B, in this sequence. We’ve already seen it trivially in the regex <code>‘ca’</code> that matches first regex <code>‘c’</code> and second regex <code>‘a’</code>. </td> </tr> </tbody> </table> </figure> <p>Note that I gave the above operators some more meaningful names (in bold) so that you can immediately grasp the purpose of each regex. For example, the <code>‘^’</code> operator is usually denoted as the ‘caret’ operator. Those names are not descriptive so I came up with more kindergarten-like words such as the “start-of-string” operator.</p> <p>Let’s dive into some examples!</p> <h2>Examples</h2> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import re text = ''' Ha! let me see her: out, alas! he's cold: Her blood is settled, and her joints are stiff; Life and these lips have long been separated: Death lies on her like an untimely frost Upon the sweetest flower of all the field. ''' print(re.findall('.a!', text)) ''' Finds all occurrences of an arbitrary character that is followed by the character sequence 'a!'. ['Ha!'] ''' print(re.findall('is.*and', text)) ''' Finds all occurrences of the word 'is', followed by an arbitrary number of characters and the word 'and'. ['is settled, and'] ''' print(re.findall('her:?', text)) ''' Finds all occurrences of the word 'her', followed by zero or one occurrences of the colon ':'. ['her:', 'her', 'her'] ''' print(re.findall('her:+', text)) ''' Finds all occurrences of the word 'her', followed by one or more occurrences of the colon ':'. ['her:'] ''' print(re.findall('^Ha.*', text)) ''' Finds all occurrences where the string starts with the character sequence 'Ha', followed by an arbitrary number of characters except for the new-line character. Can you figure out why Python doesn't find any? [] ''' print(re.findall('\n$', text)) ''' Finds all occurrences where the new-line character '\n' occurs at the end of the string. ['\n'] ''' print(re.findall('(Life|Death)', text)) ''' Finds all occurrences of either the word 'Life' or the word 'Death'. ['Life', 'Death'] ''' </pre> <p>In these examples, you’ve already seen the special symbol <code>\n</code> which denotes the new-line character in Python (and most other languages). There are many special characters, specifically designed for regular expressions.</p> <h2>Where to Go From Here</h2> <p>You’ve learned all special characters of regular expressions, as well as meta characters. This will give you a strong basis for improving your regex skills.</p> <p>If you want to accelerate your skills, you need a good foundation. Check out my brand-new Python book “<a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noreferrer noopener" aria-label="Python One-Liners (Amazon Link) (opens in a new tab)">Python One-Liners (Amazon Link)</a>” which boosts your skills from zero to hero—in a single line of Python code!</p> </div> https://www.sickgaming.net/blog/2020/02/26/regex-special-characters-examples-in-python-re/ |