在特殊字符后提取到行尾:Python

时间:2014-10-14 02:18:14

标签: python regex special-characters

我需要每行中'#'之后的字符串,所有行都有#。我已经有一个匹配该行的正则表达式,当我添加注释部分时,它不起作用。我将第一个评论后的所有行作为一个组。

行格式:

Line1 blah blah... }}#Comment1 or it could be 
Line1 blah blah...}}# Comment1 

“#”和评论之间或者没有空格。现在它匹配到第一个花括号。

我的代码:

Linepattern = re.compile(r'\{(\s*(\w+)\s*|(\w+)|(\w+)\s*)\{(.*?)\}', re.DOTALL)
for match in Linepattern.finditer(infile):
    line = matches.group(5)
    #print line
    comment = matches.group(6)
    print comment   # Returns the first comment and then the entire set of lines until end of file

我修改了我的正则表达式:

Linepattern = re.compile(r'\{(\s*(\w+)\s*|(\w+)|(\w+)\s*)\{(.*?)\}\}(#.*)?', re.DOTALL)

我看了一下这与我正在寻找的非常接近:Expression up to comment or end of line

我的输出是:

Comment1
Line2 # Comment2
Line3 # Comment3 and so on... 

我的行格式:

Foo { bar { foo=0; } }# blah1 =1, blah2=1 , blah3 =1, blah#=1
FOO { bar { bar=1;bar=2; } }#comment 2

1 个答案:

答案 0 :(得分:2)

(?<=#).+$

试试这个。参见demo.Set标志re.M

类似print re.findall(r"(?<=#).+$",x,re.M)的内容。此处x是您的测试字符串。

http://regex101.com/r/uH3tP3/3