简体   繁体   English

re.sub() 的高级使用

[英]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: 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().您可能会看到我没有关闭screen.add中的左括号,那是因为我后来关闭了它们。为此我需要使用 Python。如果可能的话,最好使用 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()?我知道可以在两个单独的 re.sub() 调用中轻松地做到这一点,但是是否可以将所有要求(删除、不触摸文本和删除文本后的)放在一个 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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