【问题标题】:Python 3: Regex doesn't work when read text from filePython 3:从文件中读取文本时,正则表达式不起作用
【发布时间】:2016-08-21 03:57:49
【问题描述】:

以下是我的资料:

输入:

 \"button\" \"button\" href=\"#\"   data-id=\"11111111111\"  \"button\" \"button\" href=\"#\"   data-id=\"222222222222\"
     \"button\" \"button\" href=\"#\"  

我想要的输出:

11111111111
222222222222

我的第一个运行良好的代码:

text = 'data-id=\"11111111111 \" data-id=\"222222222222\" '
c = re.findall('data-id=\\"(.*?)\\"', text)

我的第二个代码不起作用。什么都不显示

with open("E:/test.txt","r") as f:
    text = f.readline()

c = re.findall('data-id=\\"(.*?)\\"', text)

为什么我的辅助代码不起作用。请帮我修复它。我非常感谢你。谢谢你:)

【问题讨论】:

  • 如果你想让它工作,你的缩进是错误的。
  • 这种输入是从哪里来的?它真的看起来像 HTML 风格。
  • 请查看我的回答,了解为什么您的第一个代码有效但第二个无效。

标签: python regex file find


【解决方案1】:

请检查此答案。 (在 str_txt.txt 文件中添加了两行)。

我在您的第二个代码中所做的唯一更改是,我在正则表达式中使用 'r' 作为前缀。 更多关于 'r' 正则表达式前缀的信息,请check here !!!

import re
with open("str_txt.txt","r") as f:
    text = f.readlines()
for line in text:
    c=[]
    c = re.findall(r'data-id=\\"(.*?)\\"', line)
    print c

输出:

C:\Users\dinesh_pundkar\Desktop>python demo.Py
['11111111111', '222222222222']
['1111113434111', '222222222222']

【讨论】:

    【解决方案2】:

    你可以这样做:

    re.findall(r'"([^\\]+)\\"', s)
    
    • "([^\\]+) 匹配一个",然后捕获的组包含所需的部分,即子字符串到下一个\\\" 确保该部分后跟\\"

    示例:

    In [34]: s
    Out[34]: 'randomtext data-id=\\"11111111111\\" randomtext data-id=\\"222222222222\\"'
    
    In [35]: re.findall(r'"([^\\]+)\\"', s)
    Out[35]: ['11111111111', '222222222222']
    

    对已编辑问题的回答:

    使用\d+ 匹配数字:

    re.findall(r'"(\d+)\\"', s)
    

    改为基于 ID 匹配:

    re.findall(r'data-id=\\"([^\\]+)\\"', s)
    

    示例:

    In [45]: s
    Out[45]: '\\"button\\" \\"button\\" href=\\"#\\"   data-id=\\"11111111111\\"  \\"button\\" \\"button\\" href=\\"#\\"   data-id=\\"222222222222\\" \\"button\\" \\"button\\" href=\\"#\\"'
    
    In [50]: re.findall(r'"(\d+)\\"', s)
    Out[50]: ['11111111111', '222222222222']
    
    In [46]: re.findall(r'data-id=\\"([^\\]+)\\"', s)
    Out[46]: ['11111111111', '222222222222']
    

    【讨论】:

    • 您好,您的代码运行良好,但我的输入更复杂。我刚刚更新了这个问题。对此感到抱歉
    猜你喜欢
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-06
    • 2013-04-08
    • 2012-03-28
    • 1970-01-01
    相关资源
    最近更新 更多