Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Regex Python không phân biệt chữ hoa/thường mà không dùng re.compile

Truyền cờ re.IGNORECASE (hoặc re.I) vào tham số flags của re.search(), re.match(), re.sub().

Ví dụ

import re
print(re.search('bush', 'BuSh', re.IGNORECASE))
print(re.match('bush', 'BuSh', re.IGNORECASE))
print(re.sub('bush', 'xxxx', 'Bushmeat', flags=re.IGNORECASE))

Kết quả

<_sre.SRE_Match object at 0x...>
<_sre.SRE_Match object at 0x...>
xxxxmeat

Mẹo: Cũng có thể dùng (?i) ngay trong pattern: r'(?i)bush'.