我不会用这个正则表达式,因为同样的原因,我不会尝试用热核弹头杀死苍蝇。
假设你正在读线的时间,只是:
- 如果第一个字符是一个
#
,设置为全行注释和空行。
- 否则,请在
\
之后找到#
的第一个匹配项,然后将注释设置为加上该行的其余部分,并将该行设置为之前的所有内容。
- 用
#
替换所有出现的\#
。
就是这样,你现在有一个正确的线和评论部分。一定要用正则表达式来分割新的线段。
例如:
import re
def fn(line):
# Split line into non-comment and comment.
comment = ""
if line[0] == "#":
comment = line
line = ""
else:
idx = re.search (r"[^\\]#", line)
if idx != None:
comment = line[idx.start()+1:]
line = line[:idx.start()+1]
# Split non-comment into key and value.
idx = re.search (r"=", line)
if idx == None:
key = line
val = ""
else:
key = line[:idx.start()]
val = line[idx.start()+1:]
val = val.replace ("\\#", "#")
return (key.strip(),val.strip(),comment.strip())
print fn(r"someoption1 = some value # some comment")
print fn(r"# this line is only a comment")
print fn(r"someoption2 = some value with an escaped \# hash")
print fn(r"someoption3 = some value with a \# hash # some comment")
生产:
('someoption1', 'some value', '# some comment')
('', '', '# this line is only a comment')
('someoption2', 'some value with an escaped # hash', '')
('someoption3', 'some value with a # hash', '# some comment')
如果必须使用正则表达式(针对我的意见),您的具体问题就在这里:
[^\#]
(假设您的意思是正确转义的r"[^\\#]"
)将尝试匹配除\
或#
之外的任何字符,而不是您想要的顺序\#
。您可以使用排除查找屁股做到这一点,但我总是说,一旦正则表达式变得不可读的白痴着急,最好恢复到程序代码:-)
经过思考,一更好的方式来做到这一点是一个多层次的分裂(这样的正则表达式没有获得通过处理丢失的领域太可怕),具体如下:
def fn(line):
line = line.strip() # remove spaces
first = re.split (r"\s*(?<!\\)#\s*", line, 1) # get non-comment/comment
if len(first) == 1: first.append ("") # ensure we have a comment
first[0] = first[0].replace("\\#","#") # unescape non-comment
second = re.split (r"\s*=\s*", first[0], 1) # get key and value
if len(second) == 1: second.append ("") # ensure we have a value
second.append (first[1]) # create 3-tuple
return second # and return it
它使用负前瞻正确匹配注释分隔符将非注释位分隔为键和值。空格可以在这一个正确处理为好,得到以下特性:
['someoption1', 'some value', 'some comment']
['', '', 'this line is only a comment']
['someoption2', 'some value with an escaped # hash', '']
['someoption3', 'some value with a # hash', 'some comment']
这个问题是关于正则表达式还是关于用Python解析配置文件?如果是后者,那你为什么要编写一个配置文件解析器? Python的标准ConfigParser模块(http://docs.python.org/library/configparser.html)应该可以做到! – 2010-09-24 01:41:34
只是专门询问那个正则表达式。我只是想知道如何使用正则表达式来做到这一点。我意识到还有其他一些方法可以实现相同的目标,包括Python内置的configparser模块。虽然谢谢! – apeace 2010-09-24 01:52:28
如果你不从头开始提供不是无能的证据,回答者将承担最坏的情况:-) – 2010-09-24 02:19:49