【问题标题】:Use Python Regex to take string starting with a certain word all the way till end of line [duplicate]使用Python正则表达式以某个单词开头的字符串一直到行尾[重复]
【发布时间】:2019-07-12 16:21:36
【问题描述】:

试图从读取的文件中获取特定行,并使其成为返回的可用变量。

有关文件中数据的一些信息。语法是这样的。

A line of text I do not need  
New domain: www.example.com  
Another line that I do not need  
New domain: www.example2.com  
Ect...

它读取文件,我已经尝试了示例正则表达式模式的一系列变体,并且知道我很接近。除此之外,它相当简单。

data = []
with open('test.txt', 'r') as file: 

    data = (re.findall(r"(?<=New domain:).+$",open('test.txt'), re.M))
return data

快乐之路: 该函数从 test.txt 文件中读取,仅查看以 New domain: 开头的行,并且仅将 url 一直到行尾并将其放入列表中。

错误: 它只是告诉我模式语法是错误的。

【问题讨论】:

  • 你可以尝试去掉$re.M
  • 另外,findall 不是在那里寻找字符串。是否打开返回文件句柄?

标签: python regex


【解决方案1】:

您的正则表达式模式很好,但您不能将文件对象传递给findall。试试这个:

data = (re.findall(r"(?<=New domain:).+$", file.read(), re.M))

【讨论】:

  • Ohhhh r 是一个字符串换行。好的,谢谢大佬。对我来说,正则表达式和数据结构最难的部分是有时事情必须非常具体才能工作。
  • 由于他是在with 语句中打开文件,所以您可以直接使用file.read()
【解决方案2】:

在将文件传递给re.findall() 方法之前,您需要先读取文件。您也可以简单地使用正则表达式。

def find_domains():
    with open('test.txt', 'r+') as file:
        file_text = file.read()
        data = re.findall("New domain: (.*)", file_text)
    return data

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 2020-02-06
    • 2021-08-05
    • 2021-11-24
    • 1970-01-01
    相关资源
    最近更新 更多