python - 正则表达式:在复杂的正则表达式中平衡 "{}"(python)

标签 python regex

我尝试使用正则表达式从复杂字符串中提取信息。我尝试提取第一个 { 和最后一个 } 中的内容作为内容。不幸的是,我很难处理嵌套的 {}。如何处理这个问题?

我认为关键是平衡所有正则表达式上的 {} ,到目前为止我还没有成功......请参阅下面的括号示例: Regular expression to match balanced parentheses

import re

my_string = """
extend mineral Uraninite {
    kinetics {
        rate = -3.2e-08 mol/m2/s
        area = Uraninite
        y-term, species = Uraninite
        w-term {
            species = H[+]
            power = 0.37
        }
    }
    kinetics {
        rate = 3.2e-09 mol/m2/s
        area = Uraninite
        y-term, species = Uraninite
        w-term {
            species = H[+]
            power = 0.37
        }
    }
}
"""

regex = re.compile(
        r"extend\s+"
        r"(?:(?P<phase>colloid|mineral|basis|isotope|solid-solution)\s+)?"
        r"(?P<species>[^\n ]+)\s+"
        r"{(?P<content>[^}]*)}\n\s+}")
extend_list = [m.groupdict() for m in regex.finditer(my_string)]

到目前为止,我得到了:

print(extended_list["content"])

"""
    kinetics {
        rate = -3.2e-08 mol/m2/s
        area = Uraninite
        y-term, species = Uraninite
        w-term {
            species = H[+]
            power = 0.37
"""

看来,我需要使用正则表达式包 regex因为re不支持递归。事实上,这似乎有效:

import regex as re
pattern = re.compile(r"{(?P<content>((?:[^{}]|(?R))*))}")
extend_list2 = [m.groupdict() for m in pattern.finditer(read_data)]

print(extended_list2["content"])

"""
kinetics {
        rate = -3.2e-08 mol/m2/s
        area = Uraninite
        y-term, species = Uraninite
        w-term {
            species = H[+]
            power = 0.37
        }
    }
    kinetics {
        rate = 3.2e-09 mol/m2/s
        area = Uraninite
        y-term, species = Uraninite
        w-term {
            species = H[+]
            power = 0.37
        }
    }
"""

但是将其插入到主模式中不起作用。

pattern = re.compile(
        r"extend\s+([^n]*)"
        r"(?:(?P<phase>colloid|mineral|basis|isotope|solid-solution)\s+)?"
        r"(?P<species>[^\n ]+)\s+"
        r"{(?P<content>((?:[^{}]|(?R))*))\}")
extend_list = [m.groupdict() for m in pattern.finditer(read_data)]

最佳答案

我相信当前的正则表达式可以写成

rx = r"extend\s+(.*)(?:(?P<phase>colloid|mineral|basis|isotope|solid-solution)\s+)?(?P<species>\S+)\s+({(?P<content>((?:[^{}]++|(?4))*))})"

(?R)更改为正则表达式子例程,({(?P<content>((?:[^{}]++|(?4))*))}) 。组 ID 为 Group 4,因此子例程声明为 (?4) 。您可以快速测试一下here .

[^n]*看起来像一个错字,它匹配零个或多个非 n字符。我用过.* ,尽可能匹配除换行符之外的零个或多个字符。

[^\n ]看起来像是尝试匹配非空白 block ,因此我建议 \S在这里。

关于python - 正则表达式:在复杂的正则表达式中平衡 "{}"(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70044589/

相关文章:

Python-re.error : unterminated character set at position

正则表达式模式排除具有特定字符串的文件名

c# - c#生成单词组合数组

python - 如何对 pandas crosstab 中的行求和并制作一个新的 crosstab?

python - 如何在 python 中识别属于 numpy 数组中的集合的元素

java - 使用 Java 获取 CSS 文件中图像的 URL?

Java 正则表达式 : Grouping is not right

regex - Logwatch ignore.conf 的多行正则表达式

python - 将中间值存储在 numpy 数组中

python - intbitset __init__ 导致 SIGSEGV