Home Backend Development Python Tutorial python re正则表达式模块(Regular Expression)

python re正则表达式模块(Regular Expression)

Jun 16, 2016 am 08:43 AM
python re regular expression

模块的的作用主要是用于字符串和文本处理,查找,搜索,替换等

复习一下基本的正则表达式吧

 .:匹配除了换行符以为的任意单个字符

 *:匹配任意字符,一个,零个,多个都能匹配得到 俗称贪婪模式

+:匹配位于+之前的一个或者多个字符

 |:匹配位于|之前或者之后的字符

 ^:匹配行首

 $:匹配行尾

 ?:匹配位于?之前的零个或者一个字符,不匹配多个字符

 \:表示 \ 之后的为转义字符

 []:匹配[]之中的任意单个字符,[0-9]表示匹配0到9任意一个数字

 ():将位于()之内的的内容当作一个整体

 {}:按{}中的次数进行匹配,100[0-9]{3}表示在100之后任意匹配一个3位数(100-999)

python中以\开头的元字符:

特殊序列符号
意义
\A
只在字符串开始进行匹配
\Z
只在字符串结尾进行匹配
\b
匹配位于开始或结尾的空字符串
\B
匹配不位于开始或结尾的空字符串
\d
相当于[0-9]
\D
相当于[^0-9]
\s
匹配任意空白字符:[\t\n\r\r\v]
\S
匹配任意非空白字符:[^\t\n\r\r\v]
\w
匹配任意数字和字母:[a-zA-Z0-9]
\W
匹配任意非数字和字母:[^a-zA-Z0-9]

正则表达式语法表

语法 意义 说明
"." 任意字符
"^" 字符串开始 '^hello'匹配'helloworld'而不匹配'aaaahellobbb'
"$" 字符串结尾 与上同理
"*" 
0 个或多个字符(贪婪匹配)
匹配chinaunix
"+"
1 个或多个字符(贪婪匹配
与上同理
"?"
0 个或多个字符(贪婪匹配
与上同理
*?,+?,??
以上三个取第一个匹配结果(非贪婪匹配 匹配
{m,n}
对于前一个字符重复m到n次,{m}亦可
a{6}匹配6个a、a{2,4}匹配2到4个a
{m,n}?
对于前一个字符重复m到n次,并取尽可能少
‘aaaaaa'中a{2,4}只会匹配2个
"\\"
特殊字符转义或者特殊序列
[]
表示一个字符集 [0-9]、[a-z]、[A-Z]、[^0]
"|"
A|B,或运算
(...)
匹配括号中任意表达式
(?#...)
注释,可忽略
(?=...)
Matches if ... matches next, but doesn't consume the string.
'(?=test)'  在hellotest中匹配hello
(?!...)
Matches if ... doesn't match next.
'(?!=test)'  若hello后面不为test,匹配hello
(?
Matches if preceded by ... (must be fixed length).
'(?)test'  在hellotest中匹配test
(?
Matches if not preceded by ... (must be fixed length).
'(?test'  在hellotest中不匹配test

匹配的标志和含义

标志 含义
re.I 忽略大小写
re.L 根据本地设置而更改\w,\W,\b,\B,\s,\S的匹配内容
re.M 多行匹配模式
re.S 使“.”元字符匹配换行符
re.U 匹配Unicode字符
re.X 忽略需要匹配模式中的空格,并且可以使用"#"号注释

文本内容(提取Linux下的password文件)

man:x:6:12:man:/var/cache/man:/bin/nologin
Copy after login

re模块中有3个搜索函数,每个函数都接受3个参数(匹配模式,要匹配的字符串,进行匹配的标志),如果匹配到了就返回一个对象实例,么有就返会None.

findall():用于在字符串中查找符合正则表达式的字符串,并返回这些字符串的列表

search():搜索整个字符串,返回对象实例

match():只从第一个字符开始匹配,后面的不再匹配,返回对象实例

lovelinux@LoveLinux:~/py/boke$ cat text 
man:x:6:12:man:/var/cache/man:/bin/sh
lovelinux@LoveLinux:~/py/boke$ cat test.py
#/usr/bin/env python
#coding:utf-8
import re
with open('text','r') as txt:
 f = txt.read()
 print re.match('bin',f)
 print re.search('bin',f).end() 
lovelinux@LoveLinux:~/py/boke$ python test.py 
None
34
lovelinux@LoveLinux:~/py/boke$ vim test.py
lovelinux@LoveLinux:~/py/boke$ python test.py 
None
<_sre.SRE_Match object at 0x7f12fc9f9ed0>

Copy after login

返回是对象实例有2个方法,

start():返回记录匹配到字符的开始索引 

end():返回记录匹配到字符的结束索引

lovelinux@LoveLinux:~/py/boke$ python test.py 
None
31
34
lovelinux@LoveLinux:~/py/boke$ cat test.py 
#/usr/bin/env python
#coding:utf-8
import re
with open('text','r') as txt:
 f = txt.read()
 print re.match('bin',f)
 print re.search('bin',f).start()
 print re.search('bin',f).end()
Copy after login

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles