Skip to content
RWRui Wang / Ideas
← All notes

Learn

Interlude - Regex

Interlude - Regex cover
This is not a formal chapter, because the content in this chapter does not have a very strong relationship with the chapters before or after it, and it is not continuous. So, when divided by difficulty, this one is placed as the third Note.


In this one, we will explain a language that is very important in Python (at least in my personal opinion): Regular Expressions.


The first relatively important use of regular expressions is finding a single element that meets a requirement. Yes, it is that simple.


Here is a simple Cheat Sheet; otherwise, the later content would sound like a book from heaven.

Screenshot 2026-08-04 at 22.49.38

This is taken from Google Gemini, shout out to Google AI.


How exactly do we search? Here is a simple example. You do not need to completely understand the principle; being able to use it is enough, so I will not say too much here.

import re

text = " I am an 18-year-olguy. "
match = re.search(r'\d+')

if(match):
    print(match.group())

# So here the value assigned to Match is "18"

I will not go into why match.group() prints 18 here. Everyone can look at the table above and test themselves.


The second function: find all elements that meet the requirement.


Here is the code implementation:

import re

text = "123-453-2144 and 134-435-2323"

match = re.findall(r'\d{3}-\d{4}-\d{3}', text)

# Here match is equal to these two randomly generated phone numbers (any resemblance is purely unintentional)


The third function: replacement


Here is the implementation:

import re

text = "TheGoat: Micheal Jordan"

result = re.sub(r'TheGoat: ', '', text)
# Here result is Micheal Jordan

I personally think this function is very useful. When you are processing a lot of data and see a Title before a name, the person will become very Distinctive, which is annoying. Removing the title in front at that moment feels great.


Finally, but not limited to these functions: splitting a String


Here is the code:

import re

text = "We, Should; Seperate. the String From: Here"

result = re.split(r'[\s:;.,]', text)
# This splits a character according to the position of the index


The relatively important functions and uses of Regex are now covered. Obviously, there are still many functions I did not mention, but because of the length, I will not list them one by one. Today (8.4) produced two pieces of content, which is really quite productive. See you next time~88~