re

Python3正则表达式应用:

目的:获取匹配的字符串

输出:直接输出或是.group() / .group(0)

常用函数:

re.compile

可以把正则表达式编译成一个正则表达式对象,这样可以提高一定的效率。

import re
text = "JGood is a handsome boy, he is cool, clever, and so on..."
regex = re.compile(r'\w*oo\w*')
print regex.findall(text)   #查找所有包含'oo'的单词
print regex.sub(lambda m: '[' + m.group(0) + ']', text) #将字符串中含有'oo'的单词用[]括起来。

re.match

尝试从字符串的开始匹配一个模式

import re
text = "JGood is a handsome boy, he is cool, clever, and so on..."
m = re.match(r"(\w+)\s", text)
if m:
    print(m.group(0), '\n', m.group(1))
else:
    print('not match')

re.match的函数原型为:re.match(pattern, string, flags)

第一个参数是正则表达式,这里为"(\w+)\s",如果匹配成功,则返回一个Match,否则返回一个None

第二个参数表示要匹配的字符串;

第三个参数是标致位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等

re.search

re.search函数会在字符串内查找模式匹配,只到找到第一个匹配然后返回,如果字符串没有匹配,则返回None

import re
text = "JGood is a handsome boy, he is cool, clever, and so on..."
m = re.search(r'\shan(ds)ome\s', text)

if m:
    print(m.group(0), '\n', m.group(1))
else:
    print('not match')

re.search的函数原型为: re.search(pattern, string, flags)

每个参数的含意与re.match一样。

 

re.match与re.search的区别:

 re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;

 而re.search匹配整个字符串,直到找到一个匹配。

re.sub 

re.sub用于替换字符串中的匹配项。下面一个例子将字符串中的空格 ' ' 替换成 '-' :  

import re
text = "JGood is a handsome boy, he is cool, clever, and so on..."
print(re.sub(r'\s+', '-', text))

结果
------------------
JGood-is-a-handsome-boy,-he-is-cool,-clever,-and-so-on...

  

re.sub的函数原型为:re.sub(pattern, repl, string, count)

其中第二个函数是替换后的字符串;本例中为'-'

第四个参数指替换个数。默认为0,表示每个匹配项都替换。

re.sub还允许使用函数对匹配项的替换进行复杂的处理。如:re.sub(r'\s', lambda m: '[' + m.group(0) + ']', text, 0);将字符串中的空格' '替换为'[ ]'。

re.split

可以使用re.split来分割字符串,如:re.split(r'\s+', text);将字符串按空格分割成一个单词列表。

re.findall

re.findall可以获取字符串中所有匹配的字符串。如:re.findall(r'\w*oo\w*', text);获取字符串中,包含'oo'的所有单词

 

转载自:http://www.python8.org/a/fenleiwenzhang/yuyanjichu/2009/0901/150.html

 

转载于:https://www.cnblogs.com/AbcFly/p/6242788.html

<think>我们正在讨论Pythonre模块的匹配功能。根据引用[1][2][3][4],re模块提供了多种匹配方法,包括re.match(), re.search(), re.findall(), re.finditer()等。同时,匹配后返回的匹配对象(match object)包含了丰富的信息,如匹配的字符串、位置、分组等。 下面我将详细介绍re模块的匹配功能: ### 一、匹配方法概述 1. **`re.match(pattern, string, flags=0)`** 从字符串**开头**开始匹配,如果开头匹配成功则返回匹配对象,否则返回`None`。 **示例**: ```python import re result = re.match(r'Hello', 'Hello world!') print(result.group()) # 输出:'Hello' [^4] ``` 2. **`re.search(pattern, string, flags=0)`** 扫描整个字符串,返回**第一个**匹配成功的匹配对象,否则返回`None`。 **示例**: ```python result = re.search(r'world', 'Hello world!') print(result.group()) # 输出:'world' [^4] ``` 3. **`re.findall(pattern, string, flags=0)`** 返回所有匹配的**字符串列表**(非重叠匹配)。 **示例**: ```python result = re.findall(r'\d+', '12 apples, 34 bananas') print(result) # 输出:['12', '34'] [^3] ``` 4. **`re.finditer(pattern, string, flags=0)`** 返回一个迭代器,包含所有匹配的**匹配对象**。 **示例**: ```python matches = re.finditer(r'\d+', '12 apples, 34 bananas') for match in matches: print(match.group()) # 输出:12 然后 34 [^3] ``` ### 二、匹配对象的方法和属性 当使用`re.match()`或`re.search()`匹配成功时,会返回一个匹配对象(match object),包含以下常用方法和属性[^2]: | 方法/属性 | 说明 | |----------------|----------------------------------------------------------------------| | `group()` | 返回整个匹配的字符串(默认group(0)) | | `group(n)` | 返回第n个分组匹配的字符串(n从1开始) | | `groups()` | 返回所有分组匹配的字符串组成的元组 | | `start()` | 返回匹配的开始位置 | | `end()` | 返回匹配的结束位置 | | `span()` | 返回匹配的(start, end)位置元组 | | `lastindex` | 最后一个匹配分组的索引(如果没有分组则为None) | | `re` | 返回使用的正则表达式对象 | | `string` | 返回搜索的原始字符串 | **示例**:分组匹配 ```python pattern = r'(\d{3})-(\d{4})' # 匹配电话号码,分组区号和号码 text = '电话号码:020-1234' match = re.search(pattern, text) if match: print(f"整个匹配: {match.group()}") # 输出:'020-1234' print(f"分组1: {match.group(1)}") # 输出:'020' print(f"分组2: {match.group(2)}") # 输出:'1234' print(f"所有分组: {match.groups()}") # 输出:('020', '1234') print(f"匹配位置: {match.span()}") # 输出:(5, 13) ``` ### 三、匹配模式标志(flags) 常用标志(可通过`|`组合使用): | 标志 | 说明 | |---------------------|-------------------------------| | `re.IGNORECASE` (I) | 忽略大小写 | | `re.MULTILINE` (M) | 多行模式(影响`^`和`$`) | | `re.DOTALL` (S) | 使`.`匹配包括换行符的所有字符 | **示例**:忽略大小写匹配 ```python result = re.match(r'hello', 'HELLO world', flags=re.IGNORECASE) print(result.group()) # 输出:'HELLO' [^4] ``` ### 四、完整示例:提取网页标题 ```python import re html = ''' <html> <head><title>Python正则匹配教程</title></head> <body>...</body> </html> ''' # 匹配<title>标签内容(含多行和嵌套标签的处理) pattern = r'<title>(.*?)</title>' match = re.search(pattern, html, re.IGNORECASE | re.DOTALL) if match: title = match.group(1).strip() # 获取分组1并去除空格 print(f"网页标题: {title}") # 输出:网页标题: Python正则匹配教程 else: print("未找到标题") ``` ### 五、注意事项 1. **正则贪婪模式**:默认采用贪婪匹配(尽可能长),非贪婪模式加`?`(如`.*?`) 2. **原始字符串**:推荐使用`r'pattern'`避免转义问题(如`r'\n'`表示两个字符`\`和`n`)[^5] 3. **性能考虑**:复杂正则表达式可能引发ReDoS攻击,需谨慎设计 4. **匹配位置**:`re.match`仅从开头匹配,而`re.search`搜索整个字符串 > 正则表达式匹配的时间复杂度取决于表达式的复杂度和输入字符串的长度。简单模式匹配的时间复杂度一般为$O(n)$,但包含回溯的复杂模式可能达到指数级$O(2^n)$[^5]。 §§相关问题§§ 1. 如何解决正则表达式匹配中的贪婪模式问题? 2. 如何处理包含换行符的多行文本匹配? 3. 正则表达式匹配中的回溯是什么意思? </think>### Python re模块匹配功能详解 re模块提供多种匹配方法,用于在字符串中搜索符合正则表达式模式的子串。以下是核心匹配功能和用法: #### 一、基础匹配方法 1. **`re.match()`** - 从字符串**起始位置**匹配 ```python import re result = re.match(r'Hello', 'Hello world!') print(result.group()) # 输出:'Hello' [^4] ``` - 仅匹配开头,失败返回`None` - 示例:验证密码格式 ```python password_pattern = r'^[a-zA-Z][a-zA-Z0-9_]{5,15}$' print(re.match(password_pattern, 'k123456')) # 返回匹配对象 [^4] ``` 2. **`re.search()`** - 扫描**整个字符串**匹配 ```python result = re.search(r'world', 'Hello world!') print(result.span()) # 输出:(6, 11) [^2] ``` - 返回第一个匹配结果的位置信息 - 示例:提取HTML标签内容 ```python html = '<h1 class="name">LaoYuanPython</h1>' match = re.search(r'<h1.*?>(.*?)</h1>', html) print(match.group(1)) # 输出:LaoYuanPython [^2] ``` #### 二、多结果匹配方法 1. **`re.findall()`** - 返回所有匹配字符串列表 ```python numbers = re.findall(r'\d+', '12 apples, 34 bananas') print(numbers) # 输出:['12', '34'] [^3] ``` 2. **`re.finditer()`** - 返回匹配对象迭代器 ```python matches = re.finditer(r'\d+', '12 apples, 34 bananas') for match in matches: print(match.group(), match.span()) # 输出: # 12 (0, 2) # 34 (10, 12) [^3] ``` #### 三、匹配对象方法与属性 匹配成功后返回的匹配对象包含以下关键信息: ```python text = "订单号:AB20230815" match = re.search(r'(\w{2})(\d{8})', text) print(match.group()) # 完整匹配:'AB20230815' print(match.group(1)) # 第一分组:'AB' print(match.group(2)) # 第二分组:'20230815' [^2] print(match.groups()) # 所有分组:('AB', '20230815') print(match.start()) # 起始位置:4 print(match.end()) # 结束位置:14 print(match.span()) # 位置范围:(4, 14) [^2] ``` #### 四、匹配标志(flags) ```python # 忽略大小写匹配 re.search(r'python', 'PYTHON', flags=re.IGNORECASE).group() # 'PYTHON' # 多行模式(影响^和$行为) text = "Line1\nLine2" re.findall(r'^Line\d', text, flags=re.MULTILINE) # ['Line1', 'Line2'] [^5] ``` #### 五、分组匹配高级技巧 1. **命名分组** - 通过名称引用分组 ```python pattern = r'(?P<area>\d{3})-(?P<num>\d{4})' match = re.search(pattern, '电话:020-1234') print(match.group('area')) # '020' [^2] ``` 2. **非捕获分组** - `(?:...)`不保存分组 ```python # 匹配但不保存区号分组 re.findall(r'(?:\d{3}-)?(\d{4})', '020-1234 5678') # ['1234', '5678'] ``` #### 六、完整案例:日志解析 ```python log = "[2023-08-15 14:30:22] ERROR Module load failed (code: 500)" pattern = r'\[(?P<date>\d{4}-\d{2}-\d{2}) (?P<time>\d{2}:\d{2}:\d{2})\] (\w+) (.*?) \(code: (?P<code>\d+)\)' match = re.search(pattern, log) if match: print(f"时间: {match.group('date')} {match.group('time')}") print(f"错误码: {match.group('code')}") # 输出: # 时间: 2023-08-15 14:30:22 # 错误码: 500 ``` > 匹配效率提示:复杂模式的时间复杂度可能达到$O(2^n)$,超长文本建议使用`re.compile()`预编译[^5]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值