【问题标题】:How can I find all paths in javascript file with regex in Python?如何在 Python 中使用正则表达式查找 javascript 文件中的所有路径?
【发布时间】:2020-11-08 20:55:57
【问题描述】:

示例 Javascript(内容):

t.appendChild(u),t}},{10:10}],16:[function(e,t,r){e(10);t.exports=function(e){var t=document.createDocumentFragment(),r=document.createElement("img");r.setAttribute("alt",e.empty),r.id="trk_recaptcha",r.setAttribute("src","/cdn-cgi/images/trace/captcha/js/re/transparent.gif?ray="+e.ray),t.appendChild(r);var n=document.createTextNode(" ");t.appendChild(n);var a=document.createElement("input");a.id="id",a.setAttribute("name","id"),a.setAttribute("type","hidden"),a.setAttribute("value",e.ray),t.appendChild(a);var i=document.createTextNode(" ");t.appendChild(i);

t.appendChild(u),t}},{10:10}],16:[function(e,t,r){e(10);t.exports=function(e){var t=document.createDocumentFragment(),r=document.createElement("img");r.setAttribute("alt",e.empty),r.id="trk_recaptcha",r.setAttribute("sdfdsfsfds",'/test/path'),t.appendChild(r);var n=document.createTextNode(" ");t.appendChild(n);var a=document.createElement("input");a.id="id",a.setAttribute("name","id"),a.setAttribute("type","hidden"),a.setAttribute("value",e.ray),t.appendChild(a);var i=document.createTextNode(" ");t.appendChild(i);
regex = ""
endpoints = re.findall(regex, content)

我想要的输出:

> /cdn-cgi/images/trace/captcha/js/re/transparent.gif?ray=
> /test/path

我想用正则表达式查找以“/”和“/”开头的所有字段。我尝试了许多 url 正则表达式,但对我不起作用。

【问题讨论】:

    标签: python python-3.x regex python-re


    【解决方案1】:

    应该这样做:

    regex = r"""["']\/[^"']*"""
    

    请注意,您需要从匹配项中删除第一个字符。这也假设路径中没有引号。

    【讨论】:

    • 你能按照上面的代码示例重新排列你的代码吗?我收到“缺少结束引号”错误。
    • 这个怎么样?
    【解决方案2】:

    考虑:

    import re
    
    txt = ... #your code
    pat = r"(\"|\')(\/.*?)\1"
    
    for el in re.findall(pat, txt):
        print(el[1])
    

    每个el 都将匹配以单引号或双引号开头的模式。然后是最少数量的字符,然后是与开头相同的字符(相同类型的引号)。

    .* 代表任意数量的任意字符,? 之后使其成为非贪婪的,即提供最少的字符匹配。然后\1 引用第一组,因此它将匹配开头匹配的任何类型的引号。然后通过指定 el[1] 我们返回匹配的第二组,即引号内匹配的任何内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-19
      • 1970-01-01
      • 1970-01-01
      • 2017-03-20
      • 1970-01-01
      相关资源
      最近更新 更多