正则表达式:在字符串后的括号之间查找字符串

Regex : Find string between brackets after a string

到目前为止我的正则表达式是 ->

myRegex = /catch *\(.\) */

我希望能够搜索以下字符串 -

try {
print(new Function (astatement)())
} catch (e)  { print(e.stack) }

因此,如果 .stack 在 catch(anything) 之后存在,它应该 return 为真,到目前为止,我已经设法到达 catch(anything),从这里卡住了。

匹配 {[^}]+}

匹配异常处理程序中的简单代码,前提是没有嵌套的大括号:

catch *\((\w+)\) *{[^}]+()(\.stack)[^}]+}

上面的正则表达式匹配这些例子
(为了我的缘故捕获组,如果不需要则删除它们):

try {
  print(new Function (astatement)())
} catch (e)  { print(e.stack) }

try {
  print(new Function (bstatement)())
} catch (exception)  { print(exception.stack) }

您可以在这里试用:
https://regex101.com/r/PuytDJ/2

这里用到的一些技巧

\w+

而不是 . 我假设你可以给异常实例任何名称,所以在这里使用 \w+ 可能更安全。

{[^}]+

这会查找左大括号并捕获每个 non-closing 大括号直到下一个表达式。它仅在您的异常处理程序中没有嵌套花括号时才有效。

()

这里我引用了在捕获组 1 中找到的异常的变量名。

(\.stack)

这里是按字面意思查找.stack

[^}]+}

我继续解析所有 non-curly 个大括号字符,最后是右大括号。

免责声明

⚠ 也就是说,正则表达式不能很好地解析嵌套元素,或者只能在一定程度上解析越来越复杂的表达式。
所以代码块、HTML/XML 标签、JSON 对象等被更好地解析,而不是 text-searched in.

使用 Javascript 解析器,您可以遍历 syntax-tree (AST) 并在 catch-block.

中找到每个“.stack”

例如在Python中使用slimit

from slimit import ast
from slimit.parser import Parser
from slimit.visitors import nodevisitor


data = """
try {
    print(new Function(astatement)())
} catch (e) {
    print(e.stack)
}
"""

parser = Parser()
tree = parser.parse(data)

def nextCatch(tree):
    for node in nodevisitor.visit(tree):
        if isinstance(node, ast.Catch):
            return node


def nextIdentifierStack(tree):
    for node in nodevisitor.visit(tree):
        if isinstance(node, ast.Identifier) and node.value == 'stack':
            return node

def printChildren(node):
    for i, ch in enumerate(node.children()):
            print(f"{i:2}: {ch.to_ecma()}")


catch = nextCatch(tree)
printChildren(catch)
stack = nextIdentifierStack(catch)
print(stack.to_ecma())

打印:带有 2 children 和找到的 stack 标识符的 catch 块

 0: e
 1: {
  print(e.stack);
}
stack

另见 JavaScript parser in Python