Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Regex Special Characters – Examples in Python Re

#1
Regex Special Characters – Examples in Python Re

Regular expressions are a strange animal. Many students find them difficult to understand – do you?



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.

Regular expressions are built from characters. There are two types of characters: literal characters and special characters.

Literal Characters


Let’s start with the absolute first thing you need to know with regular expressions: a regular expression (short: regex) searches for a given pattern in a given string.

What’s a pattern? In its most basic form, a pattern can be a literal character. So the literal characters 'a', 'b', and 'c' are all valid regex patterns.

For example, you can search for the regex pattern 'a' in the string 'hello world' but it won’t find a match. You can also search for the pattern 'a' in the string 'hello woman' and there is a match: the second last character in the string.

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 'an' matches the last two characters in the string 'hello woman'.

Summary: Regular expressions are built from characters. An important class of characters are the literal characters. In principle, you can use all Unicode literal characters in your regex pattern.

Special Characters


However, the power of regular expressions come from their abstraction capability. Instead of writing the character set [abcdefghijklmnopqrstuvwxyz], you’d write [a-z] or even \w. 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.

So what are the special characters you can use in your regex patterns?

Let’s have a look at the following table that contains all special characters in Python’s re package for regular expression processing.


Special Character Meaning
\n The newline 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 'hello\nworld' matches a string where the string 'hello' is placed in one line and the string 'world' is placed into the second line. 
\t The tabular character is, like the newline character, not a “regex-specific” symbol. It just encodes the tabular space '   ' which is different to a sequence of whitespaces (even if it doesn’t look different over here). For example, the regex 'hello\n\tworld' matches the string that consists of 'hello' in the first line and ' world' in the second line (with a leading tab character).
\s The whitespace 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 '\s' simply matches any of them. For example, the regex '\s*hello\s+world' matches the string ' \t \n hello \n \n \t world', as well as 'hello world'.
\S The whitespace-negation character matches everything that does not match \s.
\w The word character regex simplifies text processing significantly. It represents the class of all characters used in typical words (A-Z, a-z, 0-9, and '_'). This simplifies the writing of complex regular expressions significantly. For example, the regex '\w+' matches the strings 'hello', 'bye', 'Python', and 'Python_is_great'
\W The word-character-negation. It matches any character that is not a word character.
\b The word boundary 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 (\w) and a non-word (\W) 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.
\d The digit character matches all numeric symbols between 0 and 9. You can use it to match integers with an arbitrary number of digits: the regex '\d+' matches integer numbers '10', '1000', '942', and '99999999999'.
\D Matches any non-digit character. This is the inverse of \d and it’s equivalent to [^0-9].

But these are not all characters you can use in a regular expression.

There are also meta characters for the regex engine that allow you to do much more powerful stuff.

A good example is the asterisk operator that matches “zero or more” occurrences of the preceding regex. For example, the pattern .*txt matches an arbitrary number of arbitrary characters followed by the suffix 'txt'. This pattern has two special regex meta characters: the dot . and the asterisk operator *. You’ll now learn about those meta characters:

Regex Meta Characters


Feel free to watch the short video about the most important regex meta characters:



Next, you’ll get a quick and dirty overview of the most important regex operations and how to use them in Python.

Here are the most important regex operators:


Meta Character Meaning
. The wild-card operator (dot) matches any character in a string except the newline character '\n'. For example, the regex '...' matches all words with three characters such as 'abc', 'cat', and 'dog'.  
* The zero-or-more asterisk operator matches an arbitrary number of occurrences (including zero occurrences) of the immediately preceding regex. For example, the regex ‘cat*’ matches the strings 'ca', 'cat', 'catt', 'cattt', and 'catttttttt'.
? The zero-or-one operator matches (as the name suggests) either zero or one occurrences of the immediately preceding regex. For example, the regex ‘cat?’ matches both strings ‘ca’ and ‘cat’ — but not ‘catt’, ‘cattt’, and ‘catttttttt’
+ The at-least-one operator matches one or more occurrences of the immediately preceding regex. For example, the regex ‘cat+’ does not match the string ‘ca’ but matches all strings with at least one trailing character ‘t’ such as ‘cat’, ‘catt’, and ‘cattt’
^ The start-of-string operator matches the beginning of a string. For example, the regex ‘^p’ would match the strings ‘python’ and ‘programming’ but not ‘lisp’ and ‘spying’ where the character ‘p’ does not occur at the start of the string.
$ The end-of-string operator matches the end of a string. For example, the regex ‘py$’ would match the strings ‘main.py’ and ‘pypy’ but not the strings ‘python’ and ‘pypi’
A|B The OR 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 ‘(hello)|(hi)’ matches strings ‘hello world’ and ‘hi python’. It wouldn’t make sense to try to match both of them at the same time.
AB  The AND operator matches first the regex A and second the regex B, in this sequence. We’ve already seen it trivially in the regex ‘ca’ that matches first regex ‘c’ and second regex ‘a’

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 ‘^’ 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.

Let’s dive into some examples!

Examples


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'] '''

In these examples, you’ve already seen the special symbol \n which denotes the new-line character in Python (and most other languages). There are many special characters, specifically designed for regular expressions.

Where to Go From Here


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.

If you want to accelerate your skills, you need a good foundation. Check out my brand-new Python book “Python One-Liners (Amazon Link)” which boosts your skills from zero to hero—in a single line of Python code!



https://www.sickgaming.net/blog/2020/02/...python-re/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] 5 Expert-Approved Ways to Remove Unicode Characters from a Python Dict xSicKxBot 0 8 5 hours ago
Last Post: xSicKxBot
  [Tut] GPT-4 with Vision (GPT-4V) Is Out! 32 Fun Examples with Screenshots xSicKxBot 0 20 Yesterday, 12:07 PM
Last Post: xSicKxBot
  [Tut] Pandas Series Object – A Helpful Guide with Examples xSicKxBot 0 1,311 05-01-2023, 01:30 AM
Last Post: xSicKxBot
  [Tut] Python Regex Capturing Groups – A Helpful Guide (+Video) xSicKxBot 0 1,412 04-07-2023, 10:07 AM
Last Post: xSicKxBot
  [Tut] How to Access Multiple Matches of a Regex Group in Python? xSicKxBot 0 1,486 04-04-2023, 02:26 PM
Last Post: xSicKxBot
  [Tut] Python | Split String with Regex xSicKxBot 0 1,411 12-13-2022, 06:04 AM
Last Post: xSicKxBot
  [Tut] Python | Split String into Characters xSicKxBot 0 1,102 10-22-2022, 02:35 AM
Last Post: xSicKxBot
  [Tut] Python RegEx – Match Whitespace But Not Newline xSicKxBot 0 1,204 08-02-2022, 09:58 PM
Last Post: xSicKxBot
  [Tut] Your Python Regex Pattern Doesn’t Match? Try This! xSicKxBot 0 1,246 05-27-2022, 01:54 AM
Last Post: xSicKxBot
  [Tut] Python Regex – ¿Cómo contar el número de coincidencias? xSicKxBot 0 1,303 04-04-2022, 12:32 AM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:

Forum software by © MyBB Theme © iAndrew 2016