Extract until end of line after a special characte

2019-02-28 23:12发布

问题:

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