假设我有一个文本文件,其中包含“我喜欢大象”这一行。
如果我捕获所述文件并将其通过管道发送到“grep大象”,我会得到整行“我喜欢大象”。
如何使用 re 在 Python 中实现此功能?
我一直在尝试以下方法:
test = re.search('elephants', 'I like elephants.\nThey are nice')
test.group(0)
我只得到“大象”这个词,而不是整个句子作为输出。
我如何获得整个句子?
谢谢。
你可以使用in
关键字来检查您的子字符串:
with open('text_file.txt', 'r') as f:
for line in f.readlines():
if 'elephant' in line:
print(line)
或者,如果你有一个字符串s
with \n
人物:
for line in s.split('\n'):
if 'elephant' in line:
print(line)
你的正则表达式只打印elephant
因为这就是它捕获的内容:正是您的正则表达式字符串。如果您要尝试以下正则表达式:
test = re.search(r'(.*?elephants.*?)\n', 'I like elephants.\nThey are nice')
然后你就会得到结果test.group(0)
and test.group(1)
其中包括大象前后的整条线。
In [22]: test.group(0)
Out[22]: 'I like elephants.\n'
这就是整个捕获的字符串。
In [23]: test.group(1)
Out[23]: 'I like elephants.'
这只是捕获组(括号之间的字符串)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)