正则表达式(Regular Expressions 或 RegEx)是用于匹配字符串模式的强大工具。在 Python 中,re 模块提供了正则表达式的支持。以下是一些基本的正则表达式用法:

1. 导入 re 模块:
import re

2. 基本匹配:
pattern = re.compile(r"apple")
text = "I like apples and oranges."
match = pattern.search(text)

if match:
    print("Match found:", match.group())
else:
    print("No match")

3. 元字符:

  •  .: 匹配任意字符。

  •  ^: 匹配字符串的开头。

  •  $: 匹配字符串的结尾。

  •  *: 匹配前一个字符零次或多次。

  •  +: 匹配前一个字符一次或多次。

  •  ?: 匹配前一个字符零次或一次。

  •  \: 转义特殊字符。

pattern = re.compile(r"^Hello")
text = "Hello, World!"

if pattern.match(text):
    print("Match found")
else:
    print("No match")

4. 字符集合:
pattern = re.compile(r"[aeiou]")
text = "This is a sample text."

matches = pattern.findall(text)
print(matches)

5. 范围和排除:
# 范围
pattern = re.compile(r"[0-9]")
text = "The price is $42."

match = pattern.search(text)
if match:
    print("Match found:", match.group())

# 排除
pattern = re.compile(r"[^0-9]")
text = "The price is $42."

match = pattern.search(text)
if match:
    print("Match found:", match.group())

6. 分组和捕获:
pattern = re.compile(r"(\w+)-(\d+)")
text = "apple-123 orange-456"

matches = pattern.findall(text)
for match in matches:
    print("Name:", match[0], "Number:", match[1])

7. 替换:
pattern = re.compile(r"\b\w+\b")
text = "This is a sample text."

replaced_text = pattern.sub("word", text)
print(replaced_text)

这些是一些基本的正则表达式用法。正则表达式是一个庞大的主题,涉及到更多高级的概念和技巧。在实际应用中,根据具体的匹配需求,你可能需要深入学习更多的正则表达式语法。


转载请注明出处:http://www.pingtaimeng.com/article/detail/13282/Python3