python 使用re模块,配合正则表达式来查找字符串的想要的字符串

发布时间 2023-08-22 16:06:04作者: 小明明007

一,首先:我们现了解一下python中正则表达式的基本规则有那些?

1,字符串"\d"匹配0~9之间的一个数值

eg: 'dsas212b321321'

使用 r'\d'

结果:(它会一次匹配一个数字依次查找)2 1 2 3 2 1 3 2 1 

 

2,字符"+"重复前面一个匹配字符一次或者多次

eg: 'dsas212b321321'

方式1:使用 r'\d+'

结果:(它会一次匹配一个数字依次查找)212  321321 

3,字符" * "重复前面一个匹配字符零次或者多次.

eg: 'dsas212b321321'

 

 

二,其次,让我们来了解一下‘re模块’有那些可查找的函数方法?

在 Python 中,使用正则表达式可以通过以下几种方法进行匹配:

  1. re.match(pattern, string, flags=0):从字符串的开头开始匹配,如果匹配成功,则返回一个匹配对象;否则返回 None。

  2. re.search(pattern, string, flags=0):在整个字符串中搜索,找到第一个匹配项即返回匹配对象;如果没有找到匹配项,则返回 None。

  3. re.findall(pattern, string, flags=0):在字符串中查找匹配某个正则表达式的所有非重叠的字符串,并返回一个包含所有匹配项的列表;如果没有找到匹配项,则返回空列表。

  4. re.finditer(pattern, string, flags=0):在字符串中查找匹配某个正则表达式的所有非重叠的字符串,并返回一个包含所有匹配对象的迭代器。

  5. re.fullmatch(pattern, string, flags=0):尝试将整个字符串与正则表达式模式进行匹配,如果匹配成功,则返回一个匹配对象;否则返回 None。

  6. re.split(pattern, string, maxsplit=0, flags=0):使用正则表达式模式作为分隔符,将字符串分割为列表,并返回列表。

  7. re.sub(pattern, repl, string, count=0, flags=0):将字符串中符合正则表达式模式的部分替换为指定的内容。

这些方法都包含一个常用的参数 flags,用于控制匹配的方式,比如是否忽略大小写、是否进行多行匹配等。

这是一个示例代码,演示了使用正则表达式进行匹配的方法:

import re

# 使用 re.match
result = re.match(r'Hello', 'Hello, World!')
print(result)  # 输出: <re.Match object; span=(0, 5), match='Hello'>

# 使用 re.search
result = re.search(r'World', 'Hello, World!')
print(result)  # 输出: <re.Match object; span=(7, 12), match='World'>

# 使用 re.findall
result = re.findall(r'\d+', '123 apples, 456 oranges, 789 bananas')
print(result)  # 输出: ['123', '456', '789']

# 使用 re.finditer
result = re.finditer(r'\b[A-Z]\w+\b', 'Hello world! This is a Test Sentence.')
for match in result:
    print(match)  # 输出: <re.Match object; span=(0, 5), match='Hello'>
                  #       <re.Match object; span=(19, 23), match='Test'>
                  #       <re.Match object; span=(24, 32), match='Sentence'>

# 使用 re.fullmatch
result = re.fullmatch(r'Hello', 'Hello, World!')
print(result)  # 输出: None

# 使用 re.split
result = re.split(r'\s', 'Hello world! This is a Test Sentence.')
print(result)  # 输出: ['Hello', 'world!', 'This', 'is', 'a', 'Test', 'Sentence.']

# 使用 re.sub
result = re.sub(r'\d', '#', '123 apples, 456 oranges, 789 bananas')
print(result)  # 输出: ### apples, ### oranges, ### bananas