简体   繁体   English

在子字符串后查找文本,直到python中的行末

[英]Find text after substring until the end of the line in python

String = """bob
123 -- things
stuff after that line"""

I need to get " things". 我需要得到“东西”。 I have tried 我努力了

 def InBetween(Substring1, Substring2, String):
    return String[(String.index(Substring1)+len(Substring1)):String.index(Substring2)]
Stuff = InBetween("--", "\n", String)

But this gives me a ValueError due to the fact that it can not get any results any way to do this? 但这给我一个ValueError,原因是它无法以任何方式获得任何结果?

Use re.search 使用re.search

>>> re.search(r'--(.*)', String).group(1)
' things'

Using string methods: 使用字符串方法:

for string in text.splitlines():
    if ' -- ' in string:
        print(string.strip().split(' -- ', 1)[1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM