python - 使用 Python 修复 HTML 字符串中的开括号问题

标签 python string

我有以下文字:

string = "<i>R</i> subspace  <i>{V.</i> generated by <i>{v<sub>1</sub>,...,v<sub>i</sub></i>, "

细心的读者可能会注意到缺少两个括号。我想知道如何使用 Python 来修复这个问题?

预期输出为:

the <i>R</i>  subspace  <i>{V.}</i> generated by <i>{v<sub>1</sub>,...,v<sub>i</sub>}</i>,

一个人可以:

  1. 检查:<i>后面是否有括号?
  2. 如果是 -> </i> 前面是否有括号?

我该如何编码?

编辑

我找到了this code ,它可以告诉你括号是否匹配。

最佳答案

以下正则表达式解决方案怎么样:

import re

string = "<i>R</i> subspace  <i>{V.</i> generated by <i>{v<sub>1</sub>,...,v<sub>i</sub></i>, "
expected = "<i>R</i> subspace  <i>{V.}</i> generated by <i>{v<sub>1</sub>,...,v<sub>i</sub>}</i>, "

fixed = re.sub(r"<(?P<tag>.*?)>({.*?)</(?P=tag)>", r"<\1>\2}</\1>", string)

print(fixed == expected) # True

这个想法是匹配一个标签后跟一个大括号,找到它的结束标签,然后使用捕获组将伴随的大括号放在结束标签之前 <\1>\2}</\1> 。分割:

< # literal opening bracket
 (?P<tag> # open a named capture group
         .*? # lazily match any characters
            ) # end named capture group
             > # literal closing bracket
              ( # open capture group 2
               { # literal opening brace
                .*? # lazily match any characters
                   ) # end capture group 2
                    < # literal opening bracket
                     / # literal slash
                      (?P=tag) # backreference to the named group
                              > # literal closing bracket

如果你只想<i> ,您可以使用re.sub(r"<i>({.*?)</i>", r"<i>\1}</i>", string) .

关于python - 使用 Python 修复 HTML 字符串中的开括号问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55641223/

相关文章:

string - 在 perl 中获取字符串的 hahes 键

c++ - 测试字符串中的空格字符...?

c# - 如何在 C# 中用单个空格替换多个空格?

python - 如何在两个 pandas 数据框之间应用函数

python - 从列表中搜索部分字符串并添加包含该部分字符串的列

python - Cython 与 Python 3.3

C# 在不使用 sort( ) 或 reverse( ) 的情况下反转字符串数组

python - 从字符串中提取坐标

Python Pyglet 使用外部字体作为标签

python - 如何最适合在网络服务器上运行的API检查其公共(public)可用性/状态