当前分类:python>>正文

用Python正则表达式匹配文本模式

来源:互联网   更新时间:2023年8月7日  

Python 笔记

一、常用的规则表达式语法

import re

str = 'abc'
result = re.findall('...',str)

print(result) # ['abc']
import re

str = 'abcabcdabcdef'
result = re.findall('.{3,5}',str)

print(result) # ['abcab', 'cdabc', 'def']
import re

str = '123abc456def'
result = re.findall('\w+',str)

print(result) # ['123abc456def']
import re

str = 'abcdefgbcde'
result = re.findall('abc|bcd',str)

print(result) # ['abc', 'bcd']

二、常用的正则表达式方法

import re

str = 'abcdefg'
result = re.match('abc', str)

if result:
  print('Matched')
else:
  print('Not matched')

# Output: Matched
import re

str = 'abcdefg'
result = re.search('bcd', str)

if result:
  print('Matched')
else:
  print('Not matched')

# Output: Matched
import re

str = '123abc456def'
result = re.findall('\d+', str)

print(result) # ['123', '456']

三、正则表达式的高级应用

import re

str = 'aaa abba abbba'
result = re.findall('(a+b+a*)', str)

print(result) # ['aaa', 'abba', 'abbba']
import re

str = 'abckdfjebcd'
result = re.findall('(?<=abc).*?(?=bcd)', str)

print(result) # ['kdfje']
import re

str = '123abc456def'
result = re.sub('\d+', 'number', str)

print(result) # 'numberabcnumberdef'

四、总结

本文固定链接:https://6yhj.com/leku-p-5263.html  版权所有,转载请保留本地址!
[猜你喜欢]

标签: 百度统计