正则表达式匹配句子中的“\t”和“\n”:file_content,但我得到这样的错误

Regex to match "\t" and "\n" in the sentence :file_content, but I got the error like this

import re
re.search('\n' | '\t',file_content)

我收到这个错误:

TypeError: unsupported operand type(s) for |: 'str' and 'str'

试试这个:

import re

text = """
\tHi
There\t!
"""
pattern = re.compile(r'[\t\n]')  # Use compile to find all instances of the pattern
matches = pattern.finditer(text)
for match in matches:
    print(match)

输出:

<re.Match object; span=(0, 1), match='\n'>
<re.Match object; span=(1, 2), match='\t'>
<re.Match object; span=(4, 5), match='\n'>
<re.Match object; span=(10, 11), match='\t'>
<re.Match object; span=(12, 13), match='\n'>

使用 [\t\n](字符集)是最合乎逻辑的方法。

假设您只想 \t\n 通过文件内容

import re
pattern = re.compile(r'[\t\n]')
matches = pattern.findall(file_content)
print matches