, .
, , :
, . .
:
import re
def fn(line):
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]
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()
first = re.split (r"\s*(?<!\\)#\s*", line, 1)
if len(first) == 1: first.append ("")
first[0] = first[0].replace("\\#","#")
second = re.split (r"\s*=\s*", first[0], 1)
if len(second) == 1: second.append ("")
second.append (first[1])
return second
, . , :
['someoption1', 'some value', 'some comment']
['', '', 'this line is only a comment']
['someoption2', 'some value with an escaped
['someoption3', 'some value with a # hash', 'some comment']