cuốn sách gpt4 ai đã làm

python - 理解 python 中正则表达式的原始字符串

In lại Tác giả: Walker 123 更新时间:2023-11-28 21:49:57 28 4
mua khóa gpt4 Nike

我在 python 3.4 中解析了很多充满换行符的文本文件。我正在寻找换行符,因为它们将我的文本分成不同的部分。这是一个文本示例:

text = 'avocat ;\n\n m. x'

我天真地开始在我的正则表达式 (RE) 中寻找带有“\N”的换行符,而没有想到反斜杠“\”是一个转义字符。然而,这证明工作正常:

>>> import re

>>> pattern1 = '\n\n'
>>> re.findall(pattern1, text)
['\n\n']

然后,我明白我应该使用双反斜杠来查找一个反斜杠。这也很好用:

>>> pattern2 = '\\n\\n'
>>> re.findall(pattern2, text)
['\n\n']

但是在 another thread ,我被告知使用原始字符串而不是常规字符串,但这种格式无法找到我正在寻找的换行符:

>>> pattern3 = r'\\n\\n'
>>> pattern3
'\\\\n\\\\n'
>>> re.findall(pattern3, text)
[]

你能帮帮我吗?为了正确匹配换行符,我对应该使用哪个 RE 之王感到有点困惑。

câu trả lời hay nhất

使用原始字符串时不要加倍反斜杠:

>>> pattern3 = r'\n\n'
>>> pattern3
'\\n\\n'
>>> re.findall(pattern3, text)
['\n\n']

关于python - 理解 python 中正则表达式的原始字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32703987/

28 4 0
Walker 123
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress