【发布时间】:2009-05-31 20:23:33
【问题描述】:
虽然这个问题类似于this thread
我认为在使用正则表达式构建代码时我可能做错了什么。
我想将一行中的任何内容匹配到注释(“#”)或行尾(如果它没有注释)。
我使用的正则表达式是:(.*)(#|$)
(.*) = 一切(#|$) = 注释或行尾
代码:
OPTION = re.compile(r'(?P<value>.*)(#|$)')
file = open('file.txt')
lines = file.read()
for line in lines.split('\n'):
get_match = OPTION.match(line)
if get_match:
line_value = get_match.group('value')
print "Match= %s" % line_value
上述方法有效,但不会删除评论。 如果文件有这样一行:
this is a line # and this is a comment
运行代码时我仍然得到整行。
我是否缺少正则表达式中的其他值/信息,还是需要更改代码?
【问题讨论】:
-
那么第一个#肯定是评论的开始?