我有一根线,看起来像这样:
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”之前,为什么会这样?另外,我不确定这是不是最好的方法来做这种寻找和替换任何建议将不胜感激。在
注意,这与“words”匹配,假设一个单词只由字母、数字和下划线组成。在
以下是对正在发生的事情的更彻底的分析:
r
表示该字符串是“原始字符串”。它阻止Python将字符解释为转义序列。例如,r"\n"
是后跟字母n的斜杠,而不是被解释为单个换行符。我喜欢在正则表达式模式中使用原始字符串,尽管这并不总是必需的。在\w*-d
的括号是一个捕获组。它向regex引擎指示应该保存组的内容以供以后使用。在\w
表示“任何字母数字字符或下划线”。在*
表示“前一项的零个或多个”。\w*
一起表示“零个或多个字母数字字符或下划线”。在-d
意思是“一个连字符后跟字母d总之,
(\w*-d)
表示“零个或多个字母数字字符或下划线,后跟连字符和字母d。保存所有这些字符以备以后使用。”第二个字符串描述应该用什么替换匹配的数据。“\“1”是指“第一个捕获组的内容”。圆括号只是普通的圆括号。总之,
(\1)
在这个上下文中的意思是“从捕获的组中获取保存的内容,将其括在括号中,并将其放回字符串中”。在如果您想匹配更多的字符,而不仅仅是字母数字和下划线,您可以将
^{pr2}$\w
替换为您想要匹配的任何字符集合。在如果还想匹配以“-d()”结尾的单词,可以用
\(\)
匹配括号对,并使用?
将其标记为可选。在如果希望括号仅在双大括号内进行,则需要如下所示:
把它分解一下:
^{pr2}$替换的
r'\1(\2)\3'
只是用 中间的圆括号。在组合起来:
输出:
注意第三个实例没有得到括号,因为它不在
{{ }}
内。在相关问题 更多 >
编程相关推荐