Python 如何使用正则表达式获取下一行
使用此代码,我可以从“Name:johndoe”中获取“johndoe” 但是,当“约翰·多伊”在下一行时,如何取回 Ex:Python 如何使用正则表达式获取下一行,python,Python,使用此代码,我可以从“Name:johndoe”中获取“johndoe” 但是,当“约翰·多伊”在下一行时,如何取回 Ex: Name: John Doe body = "Name: John Doe" p = re.compile("Name: (.*)") result = p.search(str(body)) if result: s = result.group(1) import re body = """Name: John Doe""" p =
Name:
John Doe
body = "Name: John Doe"
p = re.compile("Name: (.*)")
result = p.search(str(body))
if result:
s = result.group(1)
import re
body = """Name: John Doe"""
p = re.compile("Name:\s*\n?\r?(.*)")
result = p.search(body)
if result:
s = result.group(1)
print(s)
添加可选的换行符可能会有所帮助。--><代码>\n?\r? Ex:
Name:
John Doe
body = "Name: John Doe"
p = re.compile("Name: (.*)")
result = p.search(str(body))
if result:
s = result.group(1)
import re
body = """Name: John Doe"""
p = re.compile("Name:\s*\n?\r?(.*)")
result = p.search(body)
if result:
s = result.group(1)
print(s)
我不完全确定你需要什么,但是如果你想在给定的输入字符串中找到“<代码>某个身份不明的人<代码>任何地方,那么考虑使用<代码> R.FunDAL< <代码>:
body = "Name: John Doe\nCats don't like bats.\nBut John Doe does."
matches = re.findall(r'\bJohn Doe\b', body)
print(matches)
['John Doe', 'John Doe']
关于这个:“名称:(|\n |\r |\r\n)(.*)”?可能重复的
\s*
应该只起作用,\s
是任何白色字符,包括换行符;)所以r“Name:\s*(.*)”
(使用r,否则Python将不会传递原始字符串进行重新编译,然后可能需要多次转义)我认为Name保持不变,John Doe会改变。