我想搜索一個字符串以查看其中是否有任何 \n 或 \r 字符。如果我將正則表達式設(shè)置為 re.compile(r'(\n)') 它可以很好地查找 \n。但是,如果我嘗試執(zhí)行以下 re.compile(r'\\[nr]') 或 re.compile(r'\[nr]') 來找到任何一個,它就不起作用。我知道第二個失敗是因為 \[ 轉(zhuǎn)義了括號并讓它尋找那個。使用 r'\[nr]',調(diào)試器 (Visual Studio Code) 中的模式將搜索模式顯示為 '(\\\\[n])'。我不知道我做錯了什么。https://regex101.com/r/eZ1gT7/6#python 上的正則表達式測試器適用于:(\[nr])。提前致謝。
3 回答

MM們
TA貢獻1886條經(jīng)驗 獲得超2個贊
為什么是正則表達式?
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)
結(jié)果:
Some text without: False
Some text
with them: True
添加回答
舉報
0/150
提交
取消