我想搜索一个字符串,看看其中是否有\ n或\ r \ n字符。
如果我将正则表达式设置为re.compile(r'(\ n)'),它可以很好地找到\ n。但是,如果我尝试执行以下re.compile(r'\\ [nr]')或re.compile(r'\ [nr]')来查找其中任何一个,它就不起作用。
我理解第二个失败是因为\ [逃离括号并使其寻找它。使用r'\ [nr]'调试器中的模式(Visual Studio Code)将搜索模式显示为'(\\\\ [n])'。我不知道我做错了什么。 https://regex101.com/r/eZ1gT7/6#python的正则表达式测试程序可以正常工作:(\ [nr])。提前致谢。
当你在正则表达式中使用[]
时,它会在字面上使用任何字符。然而,\n
和\r
是单个控制字符的双字符字符串表示。你想要的是r'(\n|\r)'
\r
和\n
是字符转义符,这意味着你不能将它们拆分为正则表达式中的控制字符。但是,r"([\r\n])"
工作正常。
为什么正则表达式?
crlf = set('\r\n')
def contains_cr_lf(text):
"""Returns True if text includes linefeeds or carriage returns as characters."""
return any(x in crlf for x in text)
for t in ["Some text \t without: ","""Some text
with them: """]:
print t, contains_cr_lf(t)
结果:
Some text without: False
Some text
with them: True