Python中正则表达式的用法实例汇总
正则表达式是Python程序设计中非常实用的功能,本文就常用的正则表达式做一汇总,供大家参考之用。具体如下:
一、字符串替换
1.替换所有匹配的子串
用newstring替换subject中所有与正则表达式regex匹配的子串
result, number = re.subn(regex, newstring, subject)
2.替换所有匹配的子串(使用正则表达式对象)
reobj = re.compile(regex) result, number = reobj.subn(newstring, subject)
二、字符串拆分
1.字符串拆分
result = re.split(regex, subject)
2.字符串拆分(使用正则表示式对象)
reobj = re.compile(regex) result = reobj.split(subject)
三、匹配
下面列出Python正则表达式的几种匹配用法:
1.测试正则表达式是否匹配字符串的全部或部分
regex=ur"..." #正则表达式 if re.search(regex, subject): do_something() else: do_anotherthing()
2.测试正则表达式是否匹配整个字符串
regex=ur"...\Z" #正则表达式末尾以\Z结束 if re.match(regex, subject): do_something() else: do_anotherthing()
3. 创建一个匹配对象,然后通过该对象获得匹配细节
regex=ur"..." #正则表达式 match = re.search(regex, subject) if match: # match start: match.start() # match end (exclusive): match.end() # matched text: match.group() do_something() else: do_anotherthing()
4.获取正则表达式所匹配的子串
(Get the part of a string matched by the regex) regex=ur"..." #正则表达式 match = re.search(regex, subject) if match: result = match.group() else: result = ""
5. 获取捕获组所匹配的子串
(Get the part of a string matched by a capturing group) regex=ur"..." #正则表达式 match = re.search(regex, subject) if match: result = match.group(1) else: result = ""
6. 获取有名组所匹配的子串
(Get the part of a string matched by a named group) regex=ur"..." #正则表达式 match = re.search(regex, subject) if match: result = match.group("groupname") else: result = ""
7. 将字符串中所有匹配的子串放入数组中
(Get an array of all regex matches in a string) result = re.findall(regex, subject)
8.遍历所有匹配的子串
(Iterate over all matches in a string) for match in re.finditer(r"<(.*?)\s*.*?/\1>", subject) # match start: match.start() # match end (exclusive): match.end() # matched text: match.group()
9.通过正则表达式字符串创建一个正则表达式对象
(Create an object to use the same regex for many operations) reobj = re.compile(regex)
10.用法1的正则表达式对象版本
(use regex object for if/else branch whether (part of) a string can be matched) reobj = re.compile(regex) if reobj.search(subject): do_something() else: do_anotherthing()
11.用法2的正则表达式对象版本
(use regex object for if/else branch whether a string can be matched entirely) reobj = re.compile(r"\Z") #正则表达式末尾以\Z 结束 if reobj.match(subject): do_something() else: do_anotherthing()
12.创建一个正则表达式对象,然后通过该对象获得匹配细节
(Create an object with details about how the regex object matches (part of) a string) reobj = re.compile(regex) match = reobj.search(subject) if match: # match start: match.start() # match end (exclusive): match.end() # matched text: match.group() do_something() else: do_anotherthing()
13.用正则表达式对象获取匹配子串
(Use regex object to get the part of a string matched by the regex) reobj = re.compile(regex) match = reobj.search(subject) if match: result = match.group() else: result = ""
14.用正则表达式对象获取捕获组所匹配的子串
(Use regex object to get the part of a string matched by a capturing group) reobj = re.compile(regex) match = reobj.search(subject) if match: result = match.group(1) else: result = ""
15.用正则表达式对象获取有名组所匹配的子串
(Use regex object to get the part of a string matched by a named group) reobj = re.compile(regex) match = reobj.search(subject) if match: result = match.group("groupname") else: result = ""
16.用正则表达式对象获取所有匹配子串并放入数组
(Use regex object to get an array of all regex matches in a string) reobj = re.compile(regex) result = reobj.findall(subject)
17.通过正则表达式对象遍历所有匹配子串
(Use regex object to iterate over all matches in a string) reobj = re.compile(regex) for match in reobj.finditer(subject): # match start: match.start() # match end (exclusive): match.end() # matched text: match.group()
感兴趣的读者可以动手调试一下本文实例代码,相信会有新的收获。

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

CentOS Installing Nginx requires following the following steps: Installing dependencies such as development tools, pcre-devel, and openssl-devel. Download the Nginx source code package, unzip it and compile and install it, and specify the installation path as /usr/local/nginx. Create Nginx users and user groups and set permissions. Modify the configuration file nginx.conf, and configure the listening port and domain name/IP address. Start the Nginx service. Common errors need to be paid attention to, such as dependency issues, port conflicts, and configuration file errors. Performance optimization needs to be adjusted according to the specific situation, such as turning on cache and adjusting the number of worker processes.
