python 正则表达式re 模块的使用

文章目录:

  • 一、re模块介绍
    • 1、re模块说明
    • 2、官方文档给出的文档
    • 3、别人总结的成表格中的内容
  • 二、re模块使用介绍
    • 1、常用函数源码
    • 1、常用的函数介绍与使用
  • 三、re模块的两种使用方式

我为什么要写这个博客,我又不搞爬虫,为什么,为什么,为什么? 就当证明我学过吧 !!! 当然啦,这也可能是你看过的史上最全的re教程啦


一、re模块介绍

正则表达式就是为了利用特殊符号,快速实现字符串的匹配,或者说是字符串的过滤

1、re模块说明

正则表达式是一个特殊的字符序列,它能帮助你方便的检查一个字符串是否与某种模式匹配。

Python 自1.5版本起增加了re 模块,它提供 Perl 风格的正则表达式模式。

re 模块使 Python 语言拥有全部的正则表达式功能。

compile 函数根据一个模式字符串和可选的标志参数生成一个正则表达式对象。该对象拥有一系列方法用于正则表达式匹配和替换。
re 模块也提供了与这些方法功能完全一致的函数,这些函数使用一个模式字符串做为它们的第一个参数。

2、官方文档给出的文档

正则表达式语法:

>>> import re
>>> print(re.__doc__)
Support for regular expressions (RE).This module provides regular expression matching operations similar to
those found in Perl.  It supports both 8-bit and Unicode strings; both
the pattern and the strings being processed can contain null bytes and
characters outside the US ASCII range.Regular expressions can contain both special and ordinary characters.
Most ordinary characters, like "A", "a", or "0", are the simplest
regular expressions; they simply match themselves.  You can
concatenate ordinary characters, so last matches the string 'last'.The special characters are:"."      Matches any character except a newline."^"      Matches the start of the string."$"      Matches the end of the string or just before the newline atthe end of the string."*"      Matches 0 or more (greedy) repetitions of the preceding RE.Greedy means that it will match as many repetitions as possible."+"      Matches 1 or more (greedy) repetitions of the preceding RE."?"      Matches 0 or 1 (greedy) of the preceding RE.*?,+?,?? Non-greedy versions of the previous three special characters.{m,n}    Matches from m to n repetitions of the preceding RE.{m,n}?   Non-greedy version of the above."\\"     Either escapes special characters or signals a special sequence.[]       Indicates a set of characters.A "^" as the first character indicates a complementing set."|"      A|B, creates an RE that will match either A or B.(...)    Matches the RE inside the parentheses.The contents can be retrieved or matched later in the string.(?aiLmsux) Set the A, I, L, M, S, U, or X flag for the RE (see below).(?:...)  Non-grouping version of regular parentheses.(?P<name>...) The substring matched by the group is accessible by name.(?P=name)     Matches the text matched earlier by the group named name.(?#...)  A comment; ignored.(?=...)  Matches if ... matches next, but doesn't consume the string.(?!...)  Matches if ... doesn't match next.(?<=...) Matches if preceded by ... (must be fixed length).(?<!...) Matches if not preceded by ... (must be fixed length).(?(id/name)yes|no) Matches yes pattern if the group with id/name matched,the (optional) no pattern otherwise.The special sequences consist of "\\" and a character from the list
below.  If the ordinary character is not on the list, then the
resulting RE will match the second character.\number  Matches the contents of the group of the same number.\A       Matches only at the start of the string.\Z       Matches only at the end of the string.\b       Matches the empty string, but only at the start or end of a word.\B       Matches the empty string, but not at the start or end of a word.\d       Matches any decimal digit; equivalent to the set [0-9] inbytes patterns or string patterns with the ASCII flag.In string patterns without the ASCII flag, it will match the wholerange of Unicode digits.\D       Matches any non-digit character; equivalent to [^\d].\s       Matches any whitespace character; equivalent to [ \t\n\r\f\v] inbytes patterns or string patterns with the ASCII flag.In string patterns without the ASCII flag, it will match the wholerange of Unicode whitespace characters.\S       Matches any non-whitespace character; equivalent to [^\s].\w       Matches any alphanumeric character; equivalent to [a-zA-Z0-9_]in bytes patterns or string patterns with the ASCII flag.In string patterns without the ASCII flag, it will match therange of Unicode alphanumeric characters (letters plus digitsplus underscore).With LOCALE, it will match the set [0-9_] plus characters definedas letters for the current locale.\W       Matches the complement of \w.\\       Matches a literal backslash.This module exports the following functions:match     Match a regular expression pattern to the beginning of a string.fullmatch Match a regular expression pattern to all of a string.search    Search a string for the presence of a pattern.sub       Substitute occurrences of a pattern found in a string.subn      Same as sub, but also return the number of substitutions made.split     Split a string by the occurrences of a pattern.findall   Find all occurrences of a pattern in a string.finditer  Return an iterator yielding a match object for each match.compile   Compile a pattern into a RegexObject.purge     Clear the regular expression cache.escape    Backslash all non-alphanumerics in a string.Some of the functions in this module takes flags as optional parameters:A  ASCII       For string patterns, make \w, \W, \b, \B, \d, \Dmatch the corresponding ASCII character categories(rather than the whole Unicode categories, which is thedefault).For bytes patterns, this flag is the only availablebehaviour and needn't be specified.I  IGNORECASE  Perform case-insensitive matching.L  LOCALE      Make \w, \W, \b, \B, dependent on the current locale.M  MULTILINE   "^" matches the beginning of lines (after a newline)as well as the string."$" matches the end of lines (before a newline) as wellas the end of the string.S  DOTALL      "." matches any character at all, including the newline.X  VERBOSE     Ignore whitespace and comments for nicer looking RE's.U  UNICODE     For compatibility only. Ignored for string patterns (itis the default), and forbidden for bytes patterns.This module also defines an exception 'error'.>>>

什么,英文你看不懂,好吧,我也看不懂,哈哈哈,毕竟我六级还没有过呐,哎,我咋那么优秀呀

我自己理解的正则化表达式语法如下表格:

语法 意义
. 匹配除换行外的任意字符(如果 DOTALL 则连换行也匹配)
^ 匹配字符串开始(如果MULTILINE,也匹配换行符之后)
$ 匹配字符串结束(如果MULTILINE,也匹配换行符之前)
* 匹配0个或更多个由前面的正则表达式定义的片段,贪婪方式(尽可能多的匹配)
+ 匹配1个或更多个由前面的正则表达式定义的片段,贪婪方式
? 匹配0个或1个由前面的正则表达式定义的片段,贪婪方式
*? , +?, ?? 非贪婪版本的 *, +, 和 ? (尽可能少的匹配)
{m,n} 匹配 m 到 n 次由前面的正则表达式定义的片段,贪婪方式
{m,n}? 匹配 m 到 n 次由前面的正则表达式定义的片段,非贪婪方式
[…] 匹配方括号内内的字符集中的任意一个字符
| 等于 或
(…) 匹配括号内的表达式,也表示一个组
/number 匹配先前匹配过的组(通过序号,组自动从1-99编号)
/A 匹配字符串开始
/b 匹配单词边界
/B 匹配一个空串(非单词边界)
/d 匹配任意数字
/D 匹配任意非数字
/s 匹配任意空白字符
/S 匹配任意非空字符
/w 匹配字母数字
/W 匹配非字母数字
/Z 匹配字符串结束
// 匹配反斜杠

3、别人总结的成表格中的内容

1、表格1

2、表格2

二、re模块使用介绍

1、常用函数源码

# public interfacedef match(pattern, string, flags=0):"""Try to apply the pattern at the start of the string, returninga match object, or None if no match was found."""return _compile(pattern, flags).match(string)def fullmatch(pattern, string, flags=0):"""Try to apply the pattern to all of the string, returninga match object, or None if no match was found."""return _compile(pattern, flags).fullmatch(string)def search(pattern, string, flags=0):"""Scan through string looking for a match to the pattern, returninga match object, or None if no match was found."""return _compile(pattern, flags).search(string)def sub(pattern, repl, string, count=0, flags=0):"""Return the string obtained by replacing the leftmostnon-overlapping occurrences of the pattern in string by thereplacement repl.  repl can be either a string or a callable;if a string, backslash escapes in it are processed.  If it isa callable, it's passed the match object and must returna replacement string to be used."""return _compile(pattern, flags).sub(repl, string, count)def subn(pattern, repl, string, count=0, flags=0):"""Return a 2-tuple containing (new_string, number).new_string is the string obtained by replacing the leftmostnon-overlapping occurrences of the pattern in the sourcestring by the replacement repl.  number is the number ofsubstitutions that were made. repl can be either a string or acallable; if a string, backslash escapes in it are processed.If it is a callable, it's passed the match object and mustreturn a replacement string to be used."""return _compile(pattern, flags).subn(repl, string, count)def split(pattern, string, maxsplit=0, flags=0):"""Split the source string by the occurrences of the pattern,returning a list containing the resulting substrings.  Ifcapturing parentheses are used in pattern, then the text of allgroups in the pattern are also returned as part of the resultinglist.  If maxsplit is nonzero, at most maxsplit splits occur,and the remainder of the string is returned as the final elementof the list."""return _compile(pattern, flags).split(string, maxsplit)def findall(pattern, string, flags=0):"""Return a list of all non-overlapping matches in the string.If one or more capturing groups are present in the pattern, returna list of groups; this will be a list of tuples if the patternhas more than one group.Empty matches are included in the result."""return _compile(pattern, flags).findall(string)def finditer(pattern, string, flags=0):"""Return an iterator over all non-overlapping matches in thestring.  For each match, the iterator returns a match object.Empty matches are included in the result."""return _compile(pattern, flags).finditer(string)def compile(pattern, flags=0):"Compile a regular expression pattern, returning a pattern object."return _compile(pattern, flags)def purge():   # 净化"Clear the regular expression caches"_cache.clear()_compile_repl.cache_clear()def template(pattern, flags=0):   # 模板"Compile a template pattern, returning a pattern object"return _compile(pattern, flags|T)_alphanum_str = frozenset("_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890")
_alphanum_bytes = frozenset(b"_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890")def escape(pattern):"""Escape all the characters in pattern except ASCII letters, numbers and '_'."""if isinstance(pattern, str):alphanum = _alphanum_strs = list(pattern)for i, c in enumerate(pattern):if c not in alphanum:if c == "\000":s[i] = "\\000"else:s[i] = "\\" + creturn "".join(s)else:alphanum = _alphanum_bytess = []esc = ord(b"\\")for c in pattern:if c in alphanum:s.append(c)else:if c == 0:s.extend(b"\\000")else:s.append(esc)s.append(c)return bytes(s)

1、常用的函数介绍与使用

re的匹配语法有以下几种

  • (pattern, string, flags=0):从头开始匹配
  • re.search(pattern, string, flags=0) : 匹配包含
  • re.findall(pattern, string, flags=0): 把所有匹配到的字符放到以列表中的元素返回
  • re.split(pattern, string, maxsplit=0, flags=0): 以匹配到的字符当做列表分隔符
  • re.sub(pattern, repl, string, count=0, flags=0):匹配字符并替换
  • re.fullmatch(pattern, string, flags=0):全部匹配

1、re.match(pattern, string, flags=0):从头开始匹配

从头开始匹配,比如要匹配一个字符串中的数字,那么该字符串一定要以数字开头,eg:“2013hello”,这种是可以匹配到的,“hello2013world”,这种是匹配不到的

参数说明:

  • pattern:要匹配的模式,传入的是字符串类型,一般在前面加上r"",避免转义符影响
  • string:要匹配的字符串
  • flags:标志位,默认值为0

返回值:match对象

如果匹配到则返回一个match对象,如果没有匹配到则返回None例如:<_sre.SRE_Match object; span=(0, 4), match=‘1234’>
返回值的含义(下面其他的方法返回值含义同此,不一一介绍):

  • _sre.SRE_Match object:返回的match对象
  • span=(0, 4):匹配到字符的下标,并不包括右端点(包前不包后),即匹配到字符的小标为:0,1,2,3
  • match=‘1234’:匹配到的具体字符串

举例:

# \d 匹配数字一次 ,匹配数字的范围是[0-9],
# 如果要匹配数字多次就在后面填上一个加号 \d+obj = re.match('\d+', '1234uuasf')
print(obj)  # span=(0-3) 匹配到的字符串的范围是0-3(匹配到字符串的下标)   包前不包后   # match="1234" 匹配到的字符串
if obj:print(obj.group())obj = re.match('\d+', 'uu1234uuasf')
print(obj)  # span=(0-3) 匹配到的字符串的范围是0-3   包前不包后
if obj:print(obj.group())# 结果
<_sre.SRE_Match object; span=(0, 4), match='1234'>
1234
None

那如果想要匹配字符串中数字,但是字符串又不是以数字开头的怎么办?因为这种情况re.match()匹配返回值为None,此时就可以用re.search

2、re.search(pattern, string, flags=0) :匹配包含
会搜索整个字符串,如果有符合匹配模式的字符就可以匹配到

参数说明:

  • pattern:要匹配的模式,传入的是字符串类型,一般在前面加上r"",避免转义符影响
  • string:要匹配的字符串
  • flags:标志位,默认值为0

返回值:match对象

如果匹配到则返回一个match对象,如果没有匹配到则返回None例如:<_sre.SRE_Match object; span=(0, 4), match=‘1234’>

举例:

obj = re.search('\d+', 'uu1234uua212sf')
print(obj)  # span=(0-3) 匹配到的字符串的范围是0-3   包前不包后
if obj:print(obj.group())# 结果
<_sre.SRE_Match object; span=(2, 6), match='1234'>
1234

从上面的结果可以看出,只匹配到第一次出现的连续的数字,当再有数字出现时不会再匹配,如果想匹配多次怎么办呢(即匹配所有符合条件pattern的元素)?此时可以用re.findall()进行匹配

3、re.findall(pattern, string, flags=0):把所有匹配到的字符放到列表种返回
把所有匹配到的字符放到列表种返回

参数说明:

  • pattern:要匹配的模式,传入的是字符串类型,一般在前面加上r"",避免转义符影响
  • string:要匹配的字符串
  • flags:标志位,默认值为0

返回值:列表

如果匹配到,则返回符合字符的列表,如果没有匹配,则返回一个空列表

举例:

obj = re.findall('\d', 'uu1234uua212sf3')
print(obj) obj = re.findall('\d+', 'uu1234uua212sf3')
print(obj)  obj = re.findall('\d+', 'hasattrellow')
print(obj) # 结果
['1', '2', '3', '4', '2', '1', '2', '3']
['1234', '212', '3']
[]

4、re.split(pattern, string, maxsplit=0, flags=0): 以匹配到的字符当做列表分隔符
以匹配到的字符当做列表分隔符

参数说明:

  • pattern:要匹配的模式,传入的是字符串类型,一般在前面加上r"",避免转义符影响
  • string:要匹配的字符串
  • maxsplit:匹配符合模式的次数,默认是0,表示不限制次数
  • flags:标志位,默认值为0

返回值:列表

如果匹配到,返回值是一个分割的列表,如果没有匹配到就返回原来字符串的列表,即不分割

举例:

s='9-2*5/3+7/3*99/4*2998+10*568/14'
# 以* - +  / 为分隔符进行分割
re.split("[\*\-\/\+]", s)s='9-2*5/3+7/3*99/4*2998+10*568/14'
# maxsplit=3 只匹配到第三次,停止匹配(匹配三次,分成四个元素)
re.split("[\*\-\/\+]", s, maxsplit=3)re.split("[\*\-\/\+]", "128739oul")
# 结果
['9', '2', '5', '3', '7', '3', '99', '4', '2998', '10', '568', '14']
['9', '2', '5', '3+7/3*99/4*2998+10*568/14']
['128739oul']   # 没有匹配到就返回原来字符串的列表,即分割
  • 5、re.sub(pattern, repl, string, count=0, flags=0): 匹配字符并替换
    参数说明:
  • pattern:要匹配的模式,传入的是字符串类型,一般在前面加上r"",避免转义符影响
  • repl:要替换匹配到的字符的字符串
  • string:要匹配的字符串
  • count:替换匹配到字符串的次数,默认值为0,即不限制次数
  • flags:标志位,默认值为0

返回值:字符串

如果匹配到,返回值是一个分割的列表,如果没有匹配到就返回原来字符串的列表,即不分割

举例:

re.sub('[a-z]+','nb','中国abc123abc')re.sub('\d+','|', 'alex22tom33jack55hi',count=2)re.sub('[a-z]','nb','中国abc123abc')# 结果
'中国nb123nb'
'alex|tom|jack55hi'
'中国nbnbnb123nbnbnb'

5、 re.fullmatch(pattern, string, flags=0): 全部匹配
整个字符串匹配成功就返回re object, 否则返回None
参数说明:

  • pattern:要匹配的模式,传入的是字符串类型,一般在前面加上r"",避免转义符影响
  • string:要匹配的字符串
  • flags:标志位,默认值为0

返回值:match对象

如果匹配到则返回一个match对象,如果没有匹配到则返回None例如:<_sre.SRE_Match object; span=(0, 4), match=‘1234’>

举例:

obj = re.fullmatch('\w+@\w+\.(com|cn|edu)',"alex@oldboyedu.cn")
print(obj)
obj.group()obj = re.fullmatch('\d+', 'uu1234uua212sf')
print(obj)
if obj:print(obj.group())# 结果
'alex@oldboyedu.cn'
None

取出返回的match对象匹配到的字符串
1、用group()对象中的字符串

对于:re.match, re.serach, re.fullmatch 返回match对象的可以用group()提取匹配到的字符串
match对象.group()

  • 返回值字符串

正则表达式实战例子:
1、验证邮箱

举例:zhangsan-001@gmail.com
分析邮件名称部分:26个大小写英文字母表示为a-zA-Z
* 数字表示为0-9
* 下划线表示为_
* 中划线表示为-
由于名称是由若干个字母、数字、下划线和中划线组成,所以需要用到+表示多次出现根据以上条件得出邮件名称表达式:[a-zA-Z0-9_-]+ 分析域名部分:一般域名的规律为“[N级域名][三级域名.]二级域名.顶级域名”,比如“qq.com”、“www.qq.com”、“mp.weixin.qq.com”、“12-34.com.cn”,分析可得域名类似“** .**  .** .**”组成。“**”部分可以表示为[a-zA-Z0-9_-]+
“.**”部分可以表示为\.[a-zA-Z0-9_-]+
多个“.**”可以表示为(\.[a-zA-Z0-9_-]+)+综上所述,域名部分可以表示为[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+最终表达式: 由于邮箱的基本格式为“名称@域名”,需要使用“^”匹配邮箱的开始部分,用“$”匹配邮箱结束部分以保证邮箱前后不能有其他字符,所以最终邮箱的正则表达式为: ^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$

三、re模块的两种使用方式

参考:
1、http://www.runoob.com/python/python-reg-expressions.html
2、http://wiki.jikexueyuan.com/project/explore-python/Regular-Expressions/re.html
3、https://blog.csdn.net/lisonglisonglisong/article/details/39697137
4、https://blog.csdn.net/illegalname/article/details/77482700




♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠

python 正则表达式re 模块的使用相关推荐

  1. Python 正则表达式re模块的使用

    Python 正则表达式re模块的使用 基本上所有的编程语言都会有正则表达式,正则表达式是用来匹配一段字符串的表达式. 在Python中需要通过正则表达式对字符串进行匹配的时候,可以使用内置模块re. ...

  2. python中re模块的span,详解Python正则表达式re模块

    正则是处理字符串最常用的方法,我们编码中到处可见正则的身影. 正则大同小异,python 中的正则跟其他语言相比略有差异: 1.替换字符串时,替换的字符串可以是一个函数 2.split 函数可以指定分 ...

  3. python正则表达式re模块之findall函数

    python正则表达式re模块之findall函数 1. re.findall函数介绍 2. findall函数捕获分组 3. re.findall中正则表达式(.*?) 4. re.findall中 ...

  4. python正则表达式需要模块_使用Python正则表达式模块,让操作更加简单

    处理文本数据的一个主要任务就是创建许多以文本为基础的特性. 人们可能想要在文本中找出特定格式的内容,比如找出存在于文本中的电子邮件,或者大型文本中的电话号码. 虽然想要实现上述功能听起来很繁琐,但是如 ...

  5. Python正则表达式re模块简明笔记

    简介 正则表达式(regular expression)是可以匹配文本片段的模式.最简单的正则表达式就是普通字符串,可以匹配其自身.比如,正则表达式 'hello' 可以匹配字符串 'hello'. ...

  6. python正则表达式——re模块

    参考:python文档re --- 正则表达式操作 - Python 3.10.0 文档 目录 1.整体了解 2. 语法 3. re.match 4. re.search re.match与re.se ...

  7. python findall函数_Ramp;Python Data Science系列:数据处理(11)Python正则表达式re模块(三)...

    前言 使用正则表达式进行匹配,可以直接调用模块级函数,如match().search().findall()等,函数第一个参数是匹配的正则表达式,第二个参数则为要匹配的字符串.也可以使用re.comp ...

  8. Python正则表达式-re模块奇技淫巧

    文章目录 正则表达式 概念 构成 re模块应用 常用正则表达式 数字 字符 其他 小结 正则表达式 概念 正则表达式作为计算机科学的一个概念,通常被用来检索.替换那些符合某个规则的文本.正则表达式是对 ...

  9. 【专题】Python正则表达式re模块使用

    一.从一个需求出发 现在有一个Info.txt的文本信息: 姓名 地区 身局 体重 电话 况咏蜜 北京 171 48 13651054608 王心颜 上海 169 46 13813234424 马纤羽 ...

最新文章

  1. 失败已是过去,现在成就未来
  2. 【C/C++多线程编程之十】pthread线程私有数据
  3. centos安装python3.8
  4. 2021数模美赛LaTeX+Word论文模板更新!
  5. 【谷粒商城】全网最全笔记(1/4)
  6. 【教程】:Photoshop ps 图片批处理
  7. 超简单方法搭建Eclipse下的Android NDK
  8. 5.3 背景图层和普通图层的转换 [原创Ps教程]
  9. 计算机大学生寒假实践报告吧,大学生计算机寒假社会实践报告心得
  10. 打开eclipse时没有GBK码表怎么解决
  11. 一名毕业三年的女程序媛面试头条经验,技术总监都拍手叫好
  12. 前端常见的一些正则表达式(一定范围内数字、小数位数、手机号、中英文名字包含少数名族)
  13. word保存时内存不足
  14. 华为云隐私保护通话绑定号码 axb模式
  15. Java:企业微信推送消息到个人和部门
  16. 免费扫描计数软件哪个好,分享一个易用的工具
  17. HTML标记【各种标记的使用】!
  18. 计算机无法识别读卡器怎么办,usb读卡器读不出来怎么办,详细教您解决的办法...
  19. Android讯飞语音集成【语音评测3】
  20. 自学Python可以找到工作吗?

热门文章

  1. [maven] settings 文件 本地maven仓库
  2. win10系统修改Intel VT-x时进入不了BIOS问题
  3. C# 用文本框输入的时间段查询SQL数据库
  4. 必须熟悉的vim快捷键操作
  5. android fragment+ FragmentTabHost+viewpager 切换状态不保存的问题
  6. python入门教程完整版(懂中文就能学会)-Python入门教程完整版(懂中文就能学会)...
  7. python从入门到放弃系列恶搞短片-太惨!学Python方法用错,直接从入门到放弃!...
  8. 如何打开python的交互窗口-Python多版本情况下四种快速进入交互式命令行的操作技巧...
  9. python现在第几版-2020 年10月编程语言排行榜,Python 排名逼近第二
  10. python爬虫框架排行榜-8个最高效的Python爬虫框架,你用过几个?