Regular expression that skips single line comments?

Casey Caseyweb at gmail.com
Mon Jan 19 12:03:31 EST 2009


Another option (I cheated a little and turned sInput into a sequence
of lines, similar to what you would get reading a text file):

sInput = [
    '; $1 test1',
    '    ; test2 $2',
    '    test3 ; $3 $3 $3',
    'test4',
    '$5 test5',
    '   $6',
    '  test7 $7 test7',
]

import re
re_exp = re.compile(r'(\$.)')
re_cmt = re.compile(r'\s*;')
expansions = [exp for line in sInput for exp in re_exp.findall(line)
    if not re_cmt.match(line)]
print(expansions)

>>> ['$3', '$3', '$3', '$5', '$6', '$7']



More information about the Python-list mailing list