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中文网!

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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.

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

SublimeText3 Mac version
God-level code editing software (SublimeText3)