Python正则表达式查找双引号中带有变量的字符串
python中使用regex的代码,可以执行类似的操作 输入:Python正则表达式查找双引号中带有变量的字符串,python,regex,Python,Regex,python中使用regex的代码,可以执行类似的操作 输入: <script type="text/javascript"> (function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=
<script type="text/javascript">
(function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e)
{};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})();
window.parent.OnUploadCompleted(0,"/userfiles/abc.txt","abc.txt", "") ;</script>
with abc.txt是一个类似self.filename的变量
仅输出:/userfiles/abc.txt而不输出abc.txt
问题是userfiles也是一个变量
谢谢。/。假设:
1您需要的始终是一个txt文件
2字符串始终是包含字符的路径/
以下模式应该有效:
import re
INPUT = """<script type="text/javascript">
(function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e)
{};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})();
window.parent.OnUploadCompleted(0,"/userfiles/abc.txt","abc.txt", "") ;</script>"""
get_path = re.search(r"\"([^\"]*\/[^\"]*txt)\"",INPUT).group(1)
print(get_path)
输出:
/用户文件/abc.txt
此表达式可能适用于以下情况:
OnUploadCompleted\([0-9]+\s*,\s*\"\/(.+?)\"
我们期望的输出在这个捕获组中
测验
你试过什么吗?@DeveshKumarSingh我试过'/.'+'/'+self.filename+'[]',它能用,但我不确定它是否还能用/a/b/c/abc这样的东西。txt@Emma它的/userfiles/abc.txtI可能是错误的,但我的理解是OP希望完整路径作为输出,基本上是前双引号中的内容,他/她不需要的只是文件名,它是第二对双引号中的内容。
import re
regex = r"OnUploadCompleted\([0-9]+\s*,\s*\"\/(.+?)\""
test_str = ("<script type=\"text/javascript\">\n"
"(function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e)\n"
" {};d=d.replace(/.*?(?:\\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})();\n"
"window.parent.OnUploadCompleted(0,\"/userfiles/abc.txt\",\"abc.txt\", \"\") ;</script>")
matches = re.finditer(regex, test_str, re.MULTILINE)
for matchNum, match in enumerate(matches, start=1):
print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
for groupNum in range(0, len(match.groups())):
groupNum = groupNum + 1
print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))