Extract until end of line after a special character: Python

我们两清 提交于 2019-12-04 05:21:23

问题


I need the string after '#' in each line and all lines have the #. I already have a regex matching the line and when I add the comment part to this it doesn't work. I get all the lines after the first comment as one group.

Line format:

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

Either there is a space between the '#' and comment or no space. Right now it matches until the first curly braces.

My code:

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

I modified my regex to this:

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

I looked at this which is very close to what I am looking for : Expression up to comment or end of line

My output is :

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

My lines format:

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

回答1:


(?<=#).+$

Try this.See demo.Set flags re.M.

Something like print re.findall(r"(?<=#).+$",x,re.M).Here x is your test string.

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



来源:https://stackoverflow.com/questions/26351671/extract-until-end-of-line-after-a-special-character-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!