如何在 Python 原始字符串中匹配换行符 [英] How to match a new line character in Python raw string

查看:39
本文介绍了如何在 Python 原始字符串中匹配换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Python 原始字符串有点困惑.我知道如果我们使用原始字符串,那么它会将 '\' 视为普通的反斜杠(例如 r'\n' 将是 \code> 和 n).但是,我想知道如果我想在原始字符串中匹配一个新行字符怎么办.我试过 r'\\n',但没有用.

有人对此有什么好主意吗?

解决方案

在正则表达式中,您需要指定您处于多行模式:

<预><代码>>>>进口重新>>>s = """猫... 狗""">>>>>>re.match(r'cat\ndog',s,re.M)<_sre.SRE_Match 对象在 0xcb7c8>

请注意,re\n(原始字符串)转换为换行符.正如您在评论中指出的,您实际上并不需要 re.M 使其匹配,但它确实有助于更直观地匹配 $^:

<代码>>>re.match(r'^cat\ndog',s).group(0)'猫\n狗'>>>re.match(r'^cat$\ndog',s).group(0) #不匹配回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中AttributeError: 'NoneType' 对象没有属性 'group'>>>re.match(r'^cat$\ndog',s,re.M).group(0) #matches.'猫\n狗'

I got a little confused about Python raw string. I know that if we use raw string, then it will treat '\' as a normal backslash (ex. r'\n' would be \ and n). However, I was wondering what if I want to match a new line character in raw string. I tried r'\\n', but it didn't work.

Anybody has some good idea about this?

解决方案

In a regular expression, you need to specify that you're in multiline mode:

>>> import re
>>> s = """cat
... dog"""
>>> 
>>> re.match(r'cat\ndog',s,re.M)
<_sre.SRE_Match object at 0xcb7c8>

Notice that re translates the \n (raw string) into newline. As you indicated in your comments, you don't actually need re.M for it to match, but it does help with matching $ and ^ more intuitively:

>> re.match(r'^cat\ndog',s).group(0)
'cat\ndog'
>>> re.match(r'^cat$\ndog',s).group(0)  #doesn't match
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
>>> re.match(r'^cat$\ndog',s,re.M).group(0) #matches.
'cat\ndog'

这篇关于如何在 Python 原始字符串中匹配换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆