46

我对 Python 原始字符串有点困惑。我知道,如果我们使用原始字符串,那么它将被'\'视为正常的反斜杠(例如r'\n'\and n)。但是,我想知道如果我想匹配原始字符串中的换行符怎么办。我试过r'\\n'了,但没有用。

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

4

4 回答 4

41

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

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

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

>> 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'
于 2013-02-04T15:22:51.010 回答
14

最简单的答案是根本不使用原始字符串。您可以使用\\.

如果您在某些段中有大量反斜杠,那么您可以根据需要连接原始字符串和普通字符串:

r"some string \ with \ backslashes" "\n"

(Python 自动连接字符串文字,它们之间只有空格。)

请记住,如果您在 Windows 上使用路径,最简单的选择就是使用正斜杠 - 它仍然可以正常工作。

于 2013-02-04T15:06:24.643 回答
1

您还可以使用 [\r\n] 匹配新行

于 2018-11-06T11:41:25.513 回答
0
def clean_with_puncutation(text):    
    from string import punctuation
    import re
    punctuation_token={p:'<PUNC_'+p+'>' for p in punctuation}
    punctuation_token['<br/>']="<TOKEN_BL>"
    punctuation_token['\n']="<TOKEN_NL>"
    punctuation_token['<EOF>']='<TOKEN_EOF>'
    punctuation_token['<SOF>']='<TOKEN_SOF>'
  #punctuation_token



    regex = r"(<br/>)|(<EOF>)|(<SOF>)|[\n\!\@\#\$\%\^\&\*\(\)\[\]\
           {\}\;\:\,\.\/\?\|\`\_\\+\\\=\~\-\<\>]"

###Always put new sequence token at front to avoid overlapping results
 #text = '<EOF>!@#$%^&*()[]{};:,./<>?\|`~-= _+\<br/>\n <SOF>\ '
    text_=""

    matches = re.finditer(regex, text)

    index=0

    for match in matches:
     #print(match.group())
     #print(punctuation_token[match.group()])
     #print ("Match at index: %s, %s" % (match.start(), match.end()))
        text_=text_+ text[index:match.start()] +" " 
              +punctuation_token[match.group()]+ " "
        index=match.end()
    return text_
于 2017-12-15T16:09:22.530 回答