Editing List in Python using Regex doesn't work

Question:

i’m currently trying to edit a list that i created, it looks like this:

['n//POINTER #1 @ $3BA4 - STRING #1 @ $3DD3n#W32($3BA4)n・All enemies defeated[END-FE]', 'n//POINTER #2 @ $3BA8 - STRING #2 @ $3DECn#W32($3BA8)n・Follower dies[NLINE]n・All party members die[END-FE]', 'n//POINTER #3 @ $3BAC - STRING #3 @ $3E17n#W32($3BAC)n・Follower dies[NLINE]n・All party members die[END-FE]', 'n//POINTER #4 @ $3BB0 - STRING #4 @ $3E42n#W32($3BB0)n・All party members die[END-FE]']

Now i want to "find and replace" strings that look like this in each list item:

//POINTER #X @ $XXXX - STRING #X @ $XXXXn

I tried the following code, and according to regex101 it should find all regex items, but its not replacing them:

import re
engfile_chunks = [<list above>]
engfile_chunks_new = [re.sub(r'(\n//POINTER).+?(?=\n)', '', chunks) for chunks in engfile_chunks]

Anybody got a clue why its not working?

Asked By: Murow

||

Answers:

You are matching the literal string n (a backslash and then n), not a newline character. In your case, you don’t actually need a raw string for your regex, so you can make it a regular string and use one backslash. Then, Python will insert a newline character and it will work:

import re
engfile_chunks = [
    "n//POINTER #1 @ $3BA4 - STRING #1 @ $3DD3n#W32($3BA4)n・All enemies defeated[END-FE]",
    "n//POINTER #2 @ $3BA8 - STRING #2 @ $3DECn#W32($3BA8)n・Follower dies[NLINE]n・All party members die[END-FE]",
    "n//POINTER #3 @ $3BAC - STRING #3 @ $3E17n#W32($3BAC)n・Follower dies[NLINE]n・All party members die[END-FE]",
    "n//POINTER #4 @ $3BB0 - STRING #4 @ $3E42n#W32($3BB0)n・All party members die[END-FE]",
]
engfile_chunks_new = [re.sub("(n//POINTER).+?(?=n)", "", chunks) for chunks in engfile_chunks]
Answered By: pigrammer
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.