繁体   English   中英

如何在 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

我想用正则表达式找到所有以 "/ 和 '/ 开头的字段。我尝试了很多 url 正则表达式,但它对我不起作用。

这应该这样做:

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

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

考虑:

import re

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM