Python re.sub - replacing character when context does not match
Question: I am trying to clean up some corrupted csv-Files. One problem is that they
contain line feeds within data fields thus splitting one data set in two. I am
looking for a piece of python-code that eliminates line feeds should they not
be followed by 8 digits. My code so far:

    
    
    filetoparse = open('test.csv', encoding='utf-8')
    data = filetoparse.read()
    
    data = re.sub(r'\n(\d{8})',r'§§§\1',data)
    data = re.sub(r'\n',r'',data)
    data = re.sub(r'§§§','\n',data)
    

Basically I am using the §§§ as a placeholder for correct line feeds,
eliminate all line feeds in the data and then replace the placeholders with
line feeds again.

It does work, but is there a way to do this more elegantly?


Answer: Use a [negative lookahead
pattern](http://docs.python.org/2/library/re.html#regular-expression-syntax):

    
    
    data = re.sub(r'\n(?!\d{8})', '', data)
    

For example,

    
    
    import re
    data = '''
    12345678 foo
    bar
    baz
    12345678 foo
    '''
    data = re.sub(r'\n(?!\d{8})', '', data)
    
    print(data)
    

yields

    
    
    12345678 foobarbaz
    12345678 foo
    

