Table of Contents
This updated guide examines Re.subn in Python: Regular Expression (Regex) in Python and organizes the essential facts, background, and practical takeaways in clear American English.
Regular Expression (RegEx) , also known as a regular expression, is a segment of special characters that follow certain patterns, representing strings or a set of strings. For example:
^a.s$
The above code specifies the RegEx rule: any string with five letters, starting withaand ending withs.
ExpressionExample stringDescribe ^a.s$absNot suitable for only 3 charactersaliasMatchabyssMatchAliasInappropriate because the initial capital lettersAn abacusNot suitable because the first letter capitalizesAand more than 5 characters
Regular Expression in Python is expressed through the module, so the first thing when you want to use Regular Expression is to import the module into the program. Try with the example above:
import re pattern = '^a.s$' test_string = 'abyss' result = re.match(pattern, test_string) if result: print("Tim kiem thanh cong.") else: print("Tim kiem khong thanh cong.")
Here we have just used there.match()function to search for thetest_stringcorresponding to the pattern. The method returns the corresponding object if the search is successful, returnsNoneif not found.
Most languages support Regular Expression, including JavaScript, C #, Java, PHP, Ruby, SQL, Oracle, Perl. but most commonly used in Unix / Linux.
There are some other functions in the module to operate with RegEx. Before diving into these functions, learn more about RegEx's regular expression.
Syntax pattern used in RegEx Python
The pattern we understand is a sample object, a compiled version of a regular expression. To specify a regular expression, we use special characters, including:
[].^ $ * +?{} () |
In the example above is^and$.
Square brackets[]
Square brackets are used to represent the set of characters you want to match.
ExpressionExample stringDescribe [abc]aMatch the characteraacMatch the characteraorcHey JudeDoes not match
Here,[abc]will match if the string you passed contains any charactersa,borc.
You can also specify a range of characters using-within square brackets.
[ae]similar to[abcde].[1-4]similar to[1234].[0-39]similar to[01239].
If the first character of the set is^then all characters not defined in the set will be matched.
[^abc]means matching strings without charactersa,borc.[^0-9] means matching strings without any alphanumeric characters.
Special characters in[]will be treated as regular characters.
[(+)]matches any string with characters(,+or).
Dots.
The dot matches any regular single character except the new line character'n'.
ExpressionExample stringDescribe .aDoesn't match because there is only oneaccharacter Match because there are twoacdcharacters Match because there are two or more characters
Hats^
The caret symbol^is used to match the character topping a string.
ExpressionExample stringDescribe ^aaMatch because starting withaabcMatch because starting withabacDoes not match becauseanot the first^ababcMatch because starting withabacbDoes not match, starting withabut not the next characterb
Symbol of Dollar$
The Dollar$symbol is used to match the character that ends a string.
ExpressionExample stringDescribe a$aMatch because ending inaformulaMatches because of ending withacabDoes not match becauseanot in the last position
Asterisk*
The asterisk symbol*may match a string with or without a predefined character. This character can be repeated many times without any limit.
ExpressionExample stringDescribe ma*nmnMatch because of the previous character*may not appearmanMatch because of the full occurrence ofmaaaancharacters Match because of the previous character*may appear more oftenmainDoes not match because of a pattern,ndoes not liewomanmatching because there is a full appearance of characters
Plus sign+
The plus symbol+can match the string with one or more characters defined before it. This character can be repeated many times without any limit.
ExpressionExample stringDescribe ma+nmnDoes not match because the previous character+does not appearmanjoints because of the full occurrence ofmaaaancharacters Match because the previous character+may appear many timesmainnot match because unlike the pattern,ndoes not liewomanmatching because there is a full appearance of characters
Question mark?
The question mark icon may match a string with or without a predefined character. This character can not be repeated many times, only the amount is limited with one occurrence .
ExpressionExample stringDescribe ma?nmnMatch the previous letter?cannot appearmanMatch because of the full occurrence ofmaaaancharacters Do not match because of the previous character?can only appear 1 timemainnot match because does not resemble pattern, does not lieawomanMatches because of the full appearance of characters
Brace{}
The curly brackets use the general formula:{n,m}, representing the character before it can appear at least n times up to m times.nandmare positive integers and n<= m.
- If
nleft blank, this value defaults to 0. - If left blank
m, this value is infinite by default.
ExpressionExample stringDescribe a{2,3}abc datDoes not match because it does not meet the condition of theabc daatbecause there are 2 charactersa(a) of theaabc daaatbecause there are 2 and 3 charactersa(aa bcandd aaa t)aabc daaaatMatch because there appear 2 and 3 charactersa(aa bcandd aaa at)
Try another example: RegEx[0-9] {2, 4}This matches the string with at least 2 digits and no more than 4 digits.
ExpressionExample stringDescribe [0-9]{2,4}ab123csdeMatches because of the conditions:ab 123 csde12 and 345673Matches because the conditions:12and3456 731 and 2Not matched because the string has only 1 digit
Vertical markers|
Vertical window icon|This may match the string that exists 1 in 2 characters defined before and after it.
ExpressionExample stringDescribe a|bcdeDoes not match becausea,bdoes not appearadeMatch because the condition is satisfied,aappears:a deacdbeaMatches because the condition is satisfied,aandbappear:a cd b e a
Here,a|bmatches any string containingaorb.
Parentheses()
Parentheses()are used to group patterns together, the string will match the regular expression inside these brackets.
For example:(a|b|c)xzmatches any string withaorborcprecedingxz.
ExpressionExample stringDescribe (a|b|c)xzab xzDoes not match becauseaorbis preceded, but not inabxzwithxzabxzMatches because of the condition,bappears beforexz:a bxzaxz cabxzMatches because the condition is satisfied, bothaandbappear beforexz:axz ca bxz
Backslash
A backslash is used to exit special characters, ie when standing before a special character,will turn this character into a lowercase character, you can search for this special character in the string like other common characters.
For example:$awill match the string containing the preceding character$a. Here, the Dollar$symbol is not used to match a string that ends with the character that comes with it as in the RegEx tool,$is just a normal character.
However, a backslash will also turn a character often adjacent to the back into a special character.
For example, the case of the letterbwithout a backslash will match the lowercasebcharacters, but when it adds a backslash, it becomes a special character, does not match any any more.
Some patterns go with
1.A- Matches the characters that follow it at the beginning of the string.
ExpressionExample stringDescribe The match is because it lies in theIn the sunsequence. The match is not at the beginning of the chain
2.b- Match the characters specified at the beginning or end of the word.
ExpressionExample stringDescribe bfoofootballMatch for qualified condition,foois at the beginning ofa footballbecause of the condition,foolocated at the second word in the stringafootballDoes not match becausefoois in the middle of the word in the string. foobthe fooMatch because of the condition,foois at the end of the stringthe afoo testMatch because of the condition,foois at the end of the 2nd word inthe afooteststringthe afootestnot match becausefoois in the middle of the word in the string.
3.B- Contrary tob, matches the designated characters not at the beginning or end of the word.
ExpressionExample stringDescribe bfoofootballDoes not match becausefoois at the beginning ofa footballstringa footballnot match becausefoois at the beginning of the 2nd word in the stringafootballMatch becausefoois in the middle of the word in the string. foobthe fooDoesn't match becausefoois at the end ofthe afoo teststringthe afoo testnot match becausefoois at the end of the 2nd word inthe afooteststring becausefoois in the middle of the word in the string.
4.d- Matches with alphanumeric characters, equivalent to[0-9].
ExpressionExample stringDescribe d12abc3Matches because of the condition:12 abc 3PythonDoes not match because no integers appear
5.D- Matches non-numeric characters, equivalent to[^0-9].
ExpressionExample stringDescribe D1ab34"50Matches because of the conditions:1 ab 34 " 501345Does not match because the whole sequence of integers appears
6.s- Matches any space character, equivalent to[ tnrfv].
ExpressionExample stringDescribe Python RegExMatches because the string hasPythonRegExwhitespacePythonRegExnot match because the string has no spaces
7.S- Matches any non-whitespace character, equivalent to[^ tnrfv].
ExpressionExample stringDescribe SabMatches because the string hasa bcharactera bDoes not match because the whole string is whitespace
8.w- Match with any alphabetic and alphanumeric character, equivalent to[a-zA-Z0-9_].
Note: The underscore_also considered an alphanumeric character.
ExpressionExample stringDescribe w12&":;cMatches because the string has alphanumeric characters12&":;c%">!Does not match because the string has no alphanumeric characters
9.W- Match any character other than letters and numbers, equivalent to[^a-zA-Z0-9_].
ExpressionExample stringDescribe w1a2%cMatches because the string has non-alphanumeric characters1a2 % cPythonDoes not match because the string has only alphanumeric characters
Note: The underscore_also considered an alphanumeric character.
Tips : To build RegEx regular expressions, you can use the RegEx test tool likeregex101. This tool not only creates regular expressions but also helps you learn it more thoroughly.
Now that you understand the basics of RegEx, let's discuss how to use RegEx in Python code.
Regular Expression in Python
Regular Expression in Python is expressed via theremodule, so when you first want to use the regular expression, you need to import the module into the program.
import re
This module has a lot of methods, functions and constants to work with RegEx. TipsMake.com will list some of the best used examples along with an example so you can easily visualize and capture.
re.findall ()
The re.findall () method returns a list of strings containing all the matching pattern results.
Syntax:
findall(partern, string)
Inside:
patternis RegEx.stringis the string to match.
Example : Extract the numbers from the given string: "hello 12 hi 89. Howdy 34"
import re string = 'hello 12 hi 89. Howdy 34' pattern = 'd+' result = re.findall(pattern, string) print(result)
Results returned:
['12', '89', '34']
re.split ()
The method re.split () uses regular expressions to break strings into substring and return the list of these substring.
Syntax:
re.split(pattern, string, maxsplit)
Inside:
patternis RegEx.stringis the string to match.maxsplit(integer) is the maximum number of strings to be interrupted. If left blank, Python will match and cut all the strings that meet the criteria.
Example: Interrupting at a location with a space character:
import re string = 'The rain in Vietnam.' pattern = 's' result = re.split(pattern, string) print(result)
Results returned:
['The', 'rain', 'in', 'Vietnam.']
Example: Breaking the string in the first space character:
import re string = 'The rain in Vietnam.' pattern = 's' result = re.split(pattern, string, 1) print(result)
Result:
['The', 'rain in Vietnam.']
If the pattern is not found, re.split () returns the list containing the empty string.
re.sub ()
This is one of the most important methods used with Regular Expression
Re.sub () will replace all the results that match the pattern in the string with another content passed and return the modified string.
Syntax:
re.sub(pattern, replace, string, count)
Inside:
patternis RegEx.replaceis the content instead of the result string matching thepattern.stringis the string to match.count(integer) is the number of substitutions. If left blank, Python will treat this value to 0, match and replace all qualified strings.
For example : The program code deletes all spaces
import re # chuỗi nhiều dòng string = 'abc 12 de 23 n f45 6' # so khớp các ký tự khoảng trắng pattern = 's+' # chuỗi rỗng replace = '' new_string = re.sub(pattern, replace, string) print(new_string)
Results returned:
abc12de23f456
If no matching result is found,re.sub()will return an empty string.
For example: The program code deletes the first 2 spaces
import re # chuỗi nhiều dòng string = 'abc 12 de 23 n f45 6 n TipsMakewebsite' # so khớp các ký tự khoảng trắng pattern = 's+' replace = '' new_string = re.sub(r's+', replace, string, 2) print(new_string)
Output returns:
abc12de23 f45 6 TipsMakewebsite
re.subn ()
The re.subn () method uses the same asre.sub()above, but the returned result includes a tuple containing two values: the new string after being replaced and the number of replacements performed.
import re # chuỗi nhiều dòng string = 'abc 12 de 23 n f45 6 n TipsMakewebsite' # so khớp các ký tự khoảng trắng pattern = 's+' # chuỗi rỗng replace = '' new_string = re.subn(pattern, replace, string) print(new_string)
Results returned:
('abc12de23f456tipsmakewebsite', 6)
re.search ()
The re.search () method is used to search for strings matching the RegEx pattern. If the search succeeds, re.search () returns the matching object, otherwise, it returnsNone.
Syntax:
search(pattern, string)
Inside:
patternis RegEx.stringis the string to match.
import re string = "TipsMake.com la website ban co the hoc Python" # Kiem tra xem 'Tipsmake' co nam o dau chuoi khong match = re.search('A Tipsmake', string) if match: # nếu tồn tại chuỗi khớp print("Tim thay 'Tipsmake' nam o dau chuoi") # in ra thong bao nay else: print("'Tipsmake' khong nam o dau chuoi") # khong thi in ra thong bao nay
Results returned:
Tim thay 'Tipsmake' nam o dau chuoi
In this example,matchcontains the appropriate object that matches the pattern.
Object match
Some methods and properties are often used with match objects.
match.group ()
The group () method returns the parts of the string that match the pattern.
import re string = '39801 356, 2102 1111' pattern = '(d{3}) (d{2})' match = re.search(pattern, string) if match: #nếu tồn tại chuỗi khớp print(match.group()) # in ra kết quả else: print("Không khớp") # Không thì hiện thông báo # Output: 801 35
Here, the variablematchcontains the match object.
We have a pattern(d{3}) (d{2})divided into two small groups(d{3})and(d{2}). You can get part of the string corresponding to subgroups in this parenthesis as follows:
>>> match.group(1) '801' >>> match.group(2) '35' >>> match.group(1, 2) ('801', '35') >>> match.groups() ('801', '35')
match.start (), match.end () and match.span ()
The start () function returns the start index of the appropriate substring. Similarly, end () returns the end index of the appropriate substring.
>>> match.start() 2 >>> match.end() 8
The span () function returns tuple containing the start and end index of the appropriate string section.
>>> match.span() (2, 8)
match.re and match.string
Thereattribute of the match object will return a regular expression. Similarly, the string attribute returns the string passed in the code.
>>> match.re re.compile('(d{3}) (d{2})') >>> match.string '39801 356, 2102 1111'
Above are all the most commonly used methods in module re.
Use the prefix r before RegEx
When the prefixrorRis used before a regular expression that represents the next string it is only normal characters.
For example:'n'is a newline, andr'n'means that the string consists of two characters: backslashandn.
Backslashused to exit the characters as mentioned above. However, use prefixrfirstthen it is just a normal character.
import re string = 'n and r are escape sequences.' result = re.findall(r'[nr]', string) print(result) # Output: ['n', 'r']
Previous article: Declare @property in Python
FAQ
What is Re.subn in Python: Regular Expression (Regex) in Python about?
It provides a structured overview of re.subn in python, explains the main context, and highlights practical takeaways for readers.
Why does this topic matter?
Understanding the main concepts helps readers evaluate the issue, avoid common mistakes, and make better-informed decisions.
How should readers use this information?
Use the guidance as a practical starting point, confirm details that may have changed, and follow current product, safety, or security recommendations.
Reader Comments 0
Sign in with email or Google to join the discussion.