如何在 Python 中使用正则表达式找到 javascript 文件中的所有路径?

How can I find all paths in javascript file with regex in Python?

样本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

我想使用正则表达式查找以“/ 和 '/

应该这样做:

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

请注意,您需要 trim 匹配项中的第一个字符。这也假定路径中没有引号。

考虑:

import re

txt = ... #your code
pat = r"(\"|\')(\/.*?)"

for el in re.findall(pat, txt):
    print(el[1])

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

.* 代表任何数量的任意字符,跟随 ? 使其成为 non-greedy 即提供最少的字符匹配。然后 </code> 指的是第一组,因此它将匹配开头匹配的任何类型的引号。然后通过指定 <code>el[1] 我们 return 第二组匹配,即引号内匹配的任何内容。