简体   繁体   中英

Editing List in Python using Regex doesn't work

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

['\n//POINTER #1 @ $3BA4 - STRING #1 @ $3DD3\n#W32($3BA4)\n・All enemies defeated[END-FE]', '\n//POINTER #2 @ $3BA8 - STRING #2 @ $3DEC\n#W32($3BA8)\n・Follower dies[NLINE]\n・All party members die[END-FE]', '\n//POINTER #3 @ $3BAC - STRING #3 @ $3E17\n#W32($3BAC)\n・Follower dies[NLINE]\n・All party members die[END-FE]', '\n//POINTER #4 @ $3BB0 - STRING #4 @ $3E42\n#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 @ $XXXX\n

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?

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 @ $3DD3\n#W32($3BA4)\n・All enemies defeated[END-FE]",
    "\n//POINTER #2 @ $3BA8 - STRING #2 @ $3DEC\n#W32($3BA8)\n・Follower dies[NLINE]\n・All party members die[END-FE]",
    "\n//POINTER #3 @ $3BAC - STRING #3 @ $3E17\n#W32($3BAC)\n・Follower dies[NLINE]\n・All party members die[END-FE]",
    "\n//POINTER #4 @ $3BB0 - STRING #4 @ $3E42\n#W32($3BB0)\n・All party members die[END-FE]",
]
engfile_chunks_new = [re.sub("(\n//POINTER).+?(?=\n)", "", chunks) for chunks in engfile_chunks]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM