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

2024-05-20 02:03:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在每一行的“#”后面加一个字符串,所有行都有#。我已经有一个正则表达式匹配的行,当我添加评论部分到这不工作。我把第一条评论后的所有行作为一个组。在

行格式:

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

“#”和注释之间有空格或没有空格。现在它匹配到第一个大括号。在

我的代码:

^{pr2}$

我将正则表达式修改为:

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

Tags: or字符串re格式comment评论barit