python 递归正则匹配

需要提取“发热(低热(37.3-38°C)),乏力,腹痛(下腹痛,一侧腹痛)”中的“发热,乏力,腹痛”,即去除括号内的内容(包含括号,括号可能嵌套),好像可以用“平衡组/递归匹配”,但不知道怎么用python实现,用nestedExpr貌似可以实现。

from pyparsing import nestedExpr

def get_nested_expr(syms):
  if not syms.startwiths('('):
    syms = '(' + syms + ')' expr
= nestedExpr('', '') result = expr.parseString(syms).asList()[0] fin_res = [] for res in result: if isinstance(res, list): continue fin_res.extend(res.strip('').split('')) return ''.join(fin_res)

以下两种递归方案好像也行。

def parse(string):
    while True:
        output = re.sub(r'(?<!^)(([^()]*))(?!$)', '', string)
        if output == string:
            break
        string = output
    return output
import regex

regex.sub(r'(?!^)((?:[^()]*|(?R))+)', '', "发热(低热(37.3-38°C)),乏力,腹痛(下腹痛,一侧腹痛)")

 

参考链接:

如何在python中实现递归正则表达式? - 码客 (oomake.com)

python中递归的Regex模式 - 问答 - Python中文网 (cnpython.com)

posted @ 2022-01-21 16:51  夏天的冰棍儿  阅读(210)  评论(0编辑  收藏  举报