【问题标题】:extract substring using python regular expression使用python正则表达式提取子字符串
【发布时间】:2016-02-17 17:34:40
【问题描述】:

我正在尝试从字符串中提取像 ***.ini 这样的子字符串。 例如,我有

000012: 378:210 File=test1.ini  Cmd:send command1 
000512: 3378:990 File=test2.ini  Cmd:send command2 File=not.ini Cmd: include command

我需要提取第一个 "File=" 之后的子字符串,以及第一个 File=***.ini 之后的子字符串,即 "Cmd: ..." 直到最后。

所以我想要的结果是:

test1.ini
Cmd:send command1 

test2.ini  
Cmd:send command2 File=not.ini Cmd: include command

我试过了:

re.match("(.*) File=(.*).ini(.*)Cmd:(.*)", line, re.M\re.I)

这适用于第一行,但对于第二行, 我明白了:

test2.ini  Cmd:send command2 File=not.ini  #which is wrong, wanted is: 

test.ini

Cmd: include command

请大家帮忙。谢谢。 LJ

【问题讨论】:

  • 问题的根源是(.*) 这将贪婪地捕获所有内容,直到表达式其余部分的最后一个匹配项。

标签: python regex linux


【解决方案1】:

您可以将此正则表达式与re.findall 函数一起使用:

\bFile=(.+?\.ini)\s+(Cmd:.*)

RegEx Demo

代码:

p = re.compile(ur'\bFile=(.+?\.ini)\s+(Cmd:.*)')
print re.findall(p, input_str)

【讨论】:

    【解决方案2】:

    .* 太贪心了,也没有必要从行首开始匹配。试试这个

    re.search("File=([^\.]+.ini).*?(Cmd:.*)", line).groups()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多