在python字符串中用括号包围模式

2024-09-28 22:19:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一根线,看起来像这样:

oldString="this is my {{string-d}}" => "this is my {{(string-d)}}"
oldString2="this is my second{{ new_string-d }}" => "this is my second{{ (new_string-d) }}"
oldString2="this is my second new_string-d " => "this is my second (new_string-d) "
oldString2="this is my second new[123string]-d " => "this is my second (new[123string]-d) "

每当我看到“-d”在它后面和它所附加的单词之前,我都想加上括号。在

我写了一段代码,在字符串中寻找模式“-d”,并在找到模式后将字符串分区到“-d”之前、“-d”和“-d”后面的3个分区,然后检查“-d”之前的块,直到找到空格或“{”,然后停止并添加括号。我的代码如下: P、 我有很多文件,我从他们那里读,并试图修改字符串,上面的例子只是为了演示我在做什么。在

^{pr2}$

运行代码的结果是:

newString = "(this is my {{string-d )"

如你所见,开始的括号在“this”之前,而不是“string”之前,为什么会这样?另外,我不确定这是不是最好的方法来做这种寻找和替换任何建议将不胜感激。在


Tags: 字符串代码newstringismy模式this
2条回答
>>> import re
>>> oldString = "this is my {{string-d}}"
>>> oldString2 = "this is my second{{ new_string-d }}"
>>> re.sub(r"(\w*-d)", r"(\1)", oldString)
'this is my {{(string-d)}}'
>>> re.sub(r"(\w*-d)", r"(\1)", oldString2)
'this is my second{{ (new_string-d) }}'

注意,这与“words”匹配,假设一个单词只由字母、数字和下划线组成。在


以下是对正在发生的事情的更彻底的分析:

  • 字符串文本之前的r表示该字符串是“原始字符串”。它阻止Python将字符解释为转义序列。例如,r"\n"是后跟字母n的斜杠,而不是被解释为单个换行符。我喜欢在正则表达式模式中使用原始字符串,尽管这并不总是必需的。在
  • 围绕\w*-d的括号是一个捕获组。它向regex引擎指示应该保存组的内容以供以后使用。在
  • 序列\w表示“任何字母数字字符或下划线”。在
  • *表示“前一项的零个或多个”。\w*一起表示“零个或多个字母数字字符或下划线”。在
  • -d意思是“一个连字符后跟字母d

总之,(\w*-d)表示“零个或多个字母数字字符或下划线,后跟连字符和字母d。保存所有这些字符以备以后使用。”

第二个字符串描述应该用什么替换匹配的数据。“\“1”是指“第一个捕获组的内容”。圆括号只是普通的圆括号。总之,(\1)在这个上下文中的意思是“从捕获的组中获取保存的内容,将其括在括号中,并将其放回字符串中”。在


如果您想匹配更多的字符,而不仅仅是字母数字和下划线,您可以将\w替换为您想要匹配的任何字符集合。在

^{pr2}$

如果还想匹配以“-d()”结尾的单词,可以用\(\)匹配括号对,并使用?将其标记为可选。在

>>> re.sub(r"([\w\.\[\]]*-d(\(\))?)", r"(\1)", "{{startingHere[zero1].my_string-d() }}")
'{{(startingHere[zero1].my_string-d()) }}'

如果希望括号仅在双大括号内进行,则需要如下所示:

re.sub(r'({{\s*)([^}]*-d)(\s*}})', r'\1(\2)\3', s)

把它分解一下:

^{pr2}$

替换的r'\1(\2)\3'只是用 中间的圆括号。在

组合起来:

import re

def quote_string_d(s):
    return re.sub(r'({{\s*)([^}]*-d)(\s*}})', r'\1(\2)\3', s)

print(quote_string_d("this is my {{string-d}}"))
print(quote_string_d("this is my second{{ new_string-d }}"))
print(quote_string_d("this should not be quoted other_string-d "))

输出:

this is my {{(string-d)}}
this is my second{{ (new_string-d) }}
this should not be quoted other_string-d 

注意第三个实例没有得到括号,因为它不在{{ }}内。在

相关问题 更多 >