Home>


I want to delete (replace with "") a line that contains a specific character string defined by a regular expression.

Current state
I think that there is no problem because the defined regular expression works correctly in the search function.

import re
line1 = "$GAGSV, 1,1,00,2 * 76"
line2 = "$GBGSV, 1,1,02,13,41,247,18,21,35,308,21,1 * 76"
line3 = "$GNGGA, 014106.00,3955.4429013, N, 12312.0688793, E, 2,08,4.36,49.675, M, 28.378, M, 1.0,0000 * 5B"
line4 = "$GNGLL, 3595.4429013, N, 12312.0688793, E, 014106.00, A, D * 71"
linelist = [line1, line2, line3, line4]
pattern = re.compile (r'^ (?!. * (, N,)). * $')
for i in linelist:
    print (bool (pattern.search (i)))
# Output is as intended
# line1->True
# line2->True
# line3->False
# line4->False

However, the sub function does not match the output image and is not deleted at all.

csvtext = line1 + "\ n" + line2 + "\ n" + line3 + "\ n" + line4
t = re.sub (pattern, "", csvtext)
print (t)
# Output result
# $GAGSV, 1,1,00,2 * 76
# $GBGSV, 1,1,02,13,41,247,18,21,35,308,21,1 * 76
# $GNGGA, 014106.00,3955.4429013, N, 12312.0688793, E, 2,08,4.36,49.675, M, 28.378, M, 1.0,0000 * 5B
# $GNGLL, 39554.429013, N, 12312.0688793, E, 014106.00, A, D * 71
#Output image (output I want to do)
# (Delete)
# (Delete)
# $GNGGA, 014106.00,3955.4429013, N, 12312.0688793, E, 2,08,4.36,49.675, M, 28.378, M, 1.0,0000 * 5B
# $GNGLL, 39554.429013, N, 12312.0688793, E, 014106.00, A, D * 71


I've researched various things, but it's closed in all directions. Please professor.

  • Answer # 1

    If you process line by line, you can replace the presented pattern as it is.

    But,re.subTargets multi-line text$Must be matched to the end of each lineSo you need to have a MULTILINE mode pattern.

    -pattern = re.compile (r'^ (?!. * (, N,)). * $')
    + pattern = re.compile (r'^ (?!. * (, N,)). * $', Re.MULTILINE)

  • Answer # 2

    Because it doesn't match.

    >>>print (pattern.search (csvtext))
    None

    Because there is a pattern (, N,) if you connect them all.