【问题标题】:Regular expression to find id from JavaScript从 JavaScript 中查找 id 的正则表达式
【发布时间】:2015-04-02 21:43:28
【问题描述】:

我有一些字符串格式的 JavaScript 代码。目标就是这样一个字符串:

productPage.loadProductData("138674", "initial", "1");

如何提取“138674”?

我正在使用这条线:

from re import search as re_search, sub as re_sub, compile as re_compile
print re_search(r'productPage.loadProductData("?P<pid>\d+","?P<x>\w+","?P<n>\d+");', open_link).groupdict()["pid"]

【问题讨论】:

    标签: javascript python regex


    【解决方案1】:

    在 Python 中,(?P&lt;name&gt;regex) 被称为命名捕获组。您忘记了命名捕获组中的左大括号和右大括号。您还需要在正则表达式中转义 ( 以匹配文字 ( 符号。

    >>> s = 'productPage.loadProductData("138674","initial","1");'
    >>> print re.search(r'productPage.loadProductData\("(?P<pid>\d+)","(?P<x>\w+)","(?P<n>\d+)"\);', s).group("pid")
    138674
    

    >>> print re.search(r'productPage.loadProductData\("(?P<pid>\d+)","(?P<x>\w+)","(?P<n>\d+)"\);', s).groupdict()["pid"]
    138674
    

    【讨论】:

      【解决方案2】:

      除了基于正则表达式的方法,你可以用slimit JavaScript parser解决它:

      from slimit.ast import String
      from slimit.parser import Parser
      from slimit.visitors import nodevisitor
      
      data = 'productPage.loadProductData("138674","initial","1");'
      
      parser = Parser()
      tree = parser.parse(data)
      print next(node.value for node in nodevisitor.visit(tree) if isinstance(node, String))
      

      这将从data 变量中的JavaScript 代码中输出第一个String 节点。

      【讨论】:

      • 每次我有另一个html和另一个数据,所以这不是一个解决方案
      • 我只能使用 Beautiful Soup 和正则表达式
      • @goquartzquartz 信不信由你,这就是您所问问题的解决方案。
      • 这是我认为的解决方案,当您不能使用硬编码值和 3d 方库时 print re.search(r'productPage.loadProductData("(?P\d+)"," (?P\w+)","(?P\d+)");', s).groupdict()["pid"] 138674
      • @goquartzquartz mhm,我已经用正则表达式解决了这个问题——只是我故意发布了另一种方法来提取价值,因为我知道 Avinash 已经在研究基于正则表达式的方法。而且我不需要为此获得学分 - 这只是一个有趣的挑战和探索问题的其他可能解决方案的乐趣:)
      【解决方案3】:

      为什么要对代码做正则表达式,而不是使用专门的库来解析代码——例如Esprima

      Esprima 解析代码并以JSON 格式输出,因此您现在可以提取函数名称、传递给它的变量等。

      【讨论】:

      • 我不能使用任何 3d 派对库
      猜你喜欢
      • 1970-01-01
      • 2011-03-17
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 2015-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多