IronPython 正则表达式 | ^$ 问题

IronPython Regular Expression | ^$ issue

我有 2 个正则表达式,1 个用于提取嵌套函数(然后以相反的顺序求值),另一个用于确认它们已列入白名单以通过 eval(一旦我希望它能正常工作,我希望 XML 保存和配置要解析和评估的数据)。

这是获取函数及其参数的表达式。它一直有效,直到我添加了 |^$ 位,但我想要那个位,所以我可以 support/whitelist 不带参数的函数。

func = re.compile(r"""([^\(]*) #first group stores function name 
  \( #starting parenthesis
  \b([^\)\(\]\[\}\{]+)|^$\b #second group saves parameters passed to function
  \) #closing parenthesis
  """, re.VERBOSE)

这是白名单表达式。在我添加 ^$ 以支持不带参数的函数之前,它也一直有效。

whitelist = re.compile(r"""
  \bint|float|print|addthese|aval|^$\b #list of allowable procedures (or no procedure)
  \( #starting parenthesis
  \b[^\)\(\]\[\}\{]+|^$\b #parameters passed to function
  \) #closing parenthesis
  """,re.VERBOSE)

我正在(试图)解析这个,现在这是故意胡说八道,但只是为了证明这个概念。目的是评估列入白名单的表达式并能够处理用于数学的括号。

print(float(addthese(int(((1)+(2)+aval())),1)))

您需要一个可选的非捕获组:

([^\(]*) #first group stores function name 
\( #starting parenthesis
 (?:  # optional non-capturing group start
   \b([^\)\(\]\[\}\{]+)\b  #second group saves parameters passed to function
  )?  # optional non-capturing group end
\) #closing parenthesis

参见regex demo

(?:...)? 使整个 \b([^\)\(\]\[\}\{]+)\b 模式序列可选。

注意你过度转义了模式,你可以使用

([^(]*) #first group stores function name 
\( #starting parenthesis
 (?:  # optional non-capturing group start
   \b([^][(){}]+)\b  #second group saves parameters passed to function
  )?  # optional non-capturing group end
\) #closing parenthesis