The way to implement regular expression in Python is through the re (abbreviation for regular expression) module. You can call various methods of the re module to achieve different functions. Let’s talk about how to implement regular expression in Python through Which methods can be called by the re module, and what are the functions of these methods; there are also examples of regular expressions and the meanings of various special symbols:
1. re.sub and replace:
The full spelling of sub is substitute, which means to replace; now that we know it is to replace, it is easy to use it in examples. In fact, replace also means to replace, but their usage is not the same. , let’s use an example to explain their similarities and differences in detail:
>>> import re >>> str1 = 'Hello 111 is 222' >>> str2 = str1.replace('111','222') >>> print(str2) Hello 222 is 222 >>>
This is a simple example. If it is the following situation, replace all the numbers with 222, then use replace to implement it It is more troublesome, but it is relatively simple to implement using the sub method of the re module: (If it is a more complex operation, it may not be possible to use replace.)
>>> import re >>> str1 = 'Hello 123 is 456' >>> str2 = re.sub('\d+','222',str1) >>> print(str2) Hello 222 is 222 >>>
2. re.search() and re.match():
Match: Only matches the regular expression from the beginning of the string. If the match is successful, it returns matchobject, otherwise it returns none.
Search: Will All strings in the string try to match the regular expression. If all strings are not matched successfully, none is returned, otherwise matchobject.
The following example illustrates the similarities and differences between match and search. , also shows that in actual applications, search is still used more:
import re str = 'helloword,i am alex' if not re.match('word',str): print('cannot match') print(re.match('hello',str1).group()) print(re.search('word',str1).group()) #显示结果 cannot match hello word
str1 = 'helloword,i;am\nalex' str2 = str1.split(',') print(str2) import re str3 = re.split('[,|;|\n]',str1) print(str3) #下面是不同的输出结果 ['helloword', 'i;am\nalex'] ['helloword', 'i', 'am', 'alex']
## From this we can see the authenticity of the above.
4. findall:
The findall method basically appears at the same time as the compile method. Their usage is:
First Convert the string form of a regular expression into a pattern instance by compile, and then use the pattern instance to call the findall method to generate a match object to obtain the result. Before combining them, let's first look at the presets in the regular expression. Special character meaning:
\d matches any decimal number; it is equivalent to class [0-9].
\D matches any non-numeric character; it is equivalent to class [^0-9].
\s matches any whitespace character; it is equivalent to class ["t"n"r"f"v].
\S matches any non-whitespace character; it is equivalent to class [^ "t"n"r"f"v].
\w matches any alphanumeric character; it is equivalent to class [a-zA-Z0-9_].
\W matches any non-alphanumeric character; it is equivalent to class [^a-zA-Z0-9_].
After reading the meanings of these special characters, let’s give another example to illustrate the above argument:
import re str1 = 'asdf12dvdve4gb4' pattern1 = re.compile('\d') pattern2 = re.compile('[0-9]') mch1 = pattern1.findall(str1) mch2 = pattern2.findall(str1) print('mch1:\t%s'% mch1) print('mch2:\t%s'% mch2) #输出结果 mch1: ['1', '2', '4', '4']13 mch2: ['1', '2', '4', '4']
The above two Each example can well illustrate the above argument, and also shows that the special character \d is indeed the same as [0-9]. It can be seen from the output results, then if you don’t want to split each number Divide it into one element and put it in the list, but if you want to output 12 as a whole, then you can do this: (It is achieved by adding a + sign after \d. The + sign here means to put a Or multiple connected decimal numbers are output as a whole)
import re str1 = 'asdf12dvdve4gb4' pattern1 = re.compile('\d+') pattern2 = re.compile('[0-9]') mch1 = pattern1.findall(str1) mch2 = pattern2.findall(str1) print('mch1:\t%s'% mch1) print('mch2:\t%s'% mch2) #输出结果 mch1: ['12', '4', '4'] mch2: ['1', '2', '4', '4']
Let’s give another small example. This example combines special characters and the sub function of re to realize the string. All spaces are removed:
import re str1 = 'asd \tf12d vdve4gb4' new_str = re.sub('\s*','',str) print(new_str) #输出结果 asdf12dvdve4gb4
5. Metacharacters:
What we usually call binary The characters are; 2 metacharacters: . ^ $ * + ? { } [ ] | ( ) \
The metacharacters we first examine are "[" and "]". They are often used to specify a character category, which is a character set you want to match. Characters can be listed individually, or two given
character.
[]:元字符[]表示字符类,在一个字符类中,只有字符^、-、]和\有特殊含义。字符\仍然表示转义,字符-可以定义字符范围,字符^放在前面,表示非.(这个在上面的特殊字符示例中也有提现),
+ 匹配+号前内容1次至无限次
? 匹配?号前内容0次到1次
{m} 匹配前面的内容m次
{m,n} 匹配前面的内容m到n次
下面通过一个小例子,来阐述一下上面的字符在元字符[]中的使用:(在下面的这个例子中,要注意的有两点:一是在\d+后面的?号的含义,二是在匹配的前面加上了一个字符r,其实在这个示例中,加与不加都可以显示一样的结果)
>>> import re >>> print(re.findall(r"a(\d+?)","a123b")) ['1'] >>> print(re.findall(r"a(\d+)","a123b")) ['123'] >>>
以上所述是小编给大家介绍的python 正则表达式学习小结,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对PHP中文网的支持!
更多python 正则表达式学习小结相关文章请关注PHP中文网!

Implementing factory pattern in Python can create different types of objects by creating a unified interface. The specific steps are as follows: 1. Define a basic class and multiple inheritance classes, such as Vehicle, Car, Plane and Train. 2. Create a factory class VehicleFactory and use the create_vehicle method to return the corresponding object instance according to the type parameter. 3. Instantiate the object through the factory class, such as my_car=factory.create_vehicle("car","Tesla"). This pattern improves the scalability and maintainability of the code, but it needs to be paid attention to its complexity

In Python, the r or R prefix is used to define the original string, ignoring all escaped characters, and letting the string be interpreted literally. 1) Applicable to deal with regular expressions and file paths to avoid misunderstandings of escape characters. 2) Not applicable to cases where escaped characters need to be preserved, such as line breaks. Careful checking is required when using it to prevent unexpected output.

In Python, the __del__ method is an object's destructor, used to clean up resources. 1) Uncertain execution time: Relying on the garbage collection mechanism. 2) Circular reference: It may cause the call to be unable to be promptly and handled using the weakref module. 3) Exception handling: Exception thrown in __del__ may be ignored and captured using the try-except block. 4) Best practices for resource management: It is recommended to use with statements and context managers to manage resources.

The pop() function is used in Python to remove elements from a list and return a specified position. 1) When the index is not specified, pop() removes and returns the last element of the list by default. 2) When specifying an index, pop() removes and returns the element at the index position. 3) Pay attention to index errors, performance issues, alternative methods and list variability when using it.

Python mainly uses two major libraries Pillow and OpenCV for image processing. Pillow is suitable for simple image processing, such as adding watermarks, and the code is simple and easy to use; OpenCV is suitable for complex image processing and computer vision, such as edge detection, with superior performance but attention to memory management is required.

Implementing PCA in Python can be done by writing code manually or using the scikit-learn library. Manually implementing PCA includes the following steps: 1) centralize the data, 2) calculate the covariance matrix, 3) calculate the eigenvalues and eigenvectors, 4) sort and select principal components, and 5) project the data to the new space. Manual implementation helps to understand the algorithm in depth, but scikit-learn provides more convenient features.

Calculating logarithms in Python is a very simple but interesting thing. Let's start with the most basic question: How to calculate logarithm in Python? Basic method of calculating logarithm in Python The math module of Python provides functions for calculating logarithm. Let's take a simple example: importmath# calculates the natural logarithm (base is e) x=10natural_log=math.log(x)print(f"natural log({x})={natural_log}")# calculates the logarithm with base 10 log_base_10=math.log10(x)pri

To implement linear regression in Python, we can start from multiple perspectives. This is not just a simple function call, but involves a comprehensive application of statistics, mathematical optimization and machine learning. Let's dive into this process in depth. The most common way to implement linear regression in Python is to use the scikit-learn library, which provides easy and efficient tools. However, if we want to have a deeper understanding of the principles and implementation details of linear regression, we can also write our own linear regression algorithm from scratch. The linear regression implementation of scikit-learn uses scikit-learn to encapsulate the implementation of linear regression, allowing us to easily model and predict. Here is a use sc


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
