简体   繁体   中英

Advanced use of re.sub()

I want to make an Algorithm that will if requirements are met, delete the part of the text and leave one part of it and add at second part of it specific ending.

Example:

screen.add(SUBTITLES("Remove the Pirates from the Ship"), {}, function()

Output:

screen.add("Remove the Pirates from the Ship", {}, function()

Requirements: Text we want to delete will be Uppercase written. It will start after ( . It needs to have (" after finish. We want leave text between "" untouched and delete the ) at the end because it isn't needed there.

You will probably see that I didn't close the opening brackets from the screen.add , that's because I closed them later.I need to use Python for this.If it's possible, it would be nice to use re.sub(). I know it's possible to do this easily in two seperate re.sub() calls, but is it possible to put all requirements (delete, not touching the text and deleting the ) after the text ) in one re.sub()?

If the quoted part is the only thing that will appear between parentheses, and that quoted part does not have double quotes itself (escaped maybe?), then this could do it:

import re

s = """screen.add(SUBTITLES("Remove the Pirates from the Ship"), {}, function()"""
result = re.sub(r'\([A-Z]+\(("[^"]*")\)', r'(\1', s)

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