在 Python 中,可以通过在正则表达式模式字符串前面添加修饰符标志来启用修饰符功能。常用的修饰符标志包括:

  • re.I:忽略大小写匹配
  • re.M:多行匹配
  • re.S:使 . 匹配包括换行符在内的所有字符
  • re.X:忽略正则表达式中的空格和注释

可以使用 '|' 符号将多个修饰符标志组合在一起。例如:

import re

# 忽略大小写匹配
pattern1 = re.compile('hello', re.I)
result1 = pattern1.findall('Hello, world! hello')
print(result1)  # ['Hello', 'hello']

# 多行匹配
pattern2 = re.compile('^hello', re.M)
result2 = pattern2.findall('hello\nworld\nhello\n')
print(result2)  # ['hello', 'hello']

# 使 . 匹配包括换行符在内的所有字符
pattern3 = re.compile('hello.world', re.S)
result3 = pattern3.findall('hello\nworld')
print(result3)  # ['hello\nworld']

# 忽略正则表达式中的空格和注释
pattern4 = re.compile(r'''
    hello     # 匹配 hello
    \s+       # 匹配空格或制表符
    world     # 匹配 world
''', re.X)
result4 = pattern4.findall('hello   world')
print(result4)  # ['hello   world']
Python 正则表达式修饰符详解:如何使用 re.I、re.M、re.S 和 re.X

原文地址: https://www.cveoy.top/t/topic/m5ML 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录