如何在Python正则表达式中忽略模式的一部分大小写,而不是整个表达式?

bluesky1年前 ⋅ 121 阅读

ChatGPT的回答仅作参考:

可以使用re.IGNORECASE标志来忽略正则表达式中的大小写。例如,如果要匹配单词"hello",但不关心大小写,可以使用以下代码:

```python
import re

text = "Hello, world!"
pattern = re.compile(r"hello", re.IGNORECASE)
match = pattern.search(text)
if match:
    print("Match found!")
else:
    print("Match not found.")
```

在这个例子中,re.IGNORECASE标志告诉Python忽略正则表达式中的大小写。因此,无论文本中的"hello"是大写还是小写,都会被匹配。

全部评论: 0

    相关推荐