【问题标题】:Python Regex to find a string with varible in double quotesPython正则表达式在双引号中查找带有变量的字符串
【发布时间】:2019-06-26 03:53:57
【问题描述】:

使用正则表达式的python代码可以执行类似的操作

输入:

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

带有 abc.txt 的变量类似于 self.filename

仅输出:/userfiles/abc.txt 没有 abc.txt

问题是userfiles 也是一个变量。

谢谢。/。

【问题讨论】:

  • 你有什么尝试吗?
  • @DeveshKumarSingh 我尝试'"/.*' + '/' + self.filename + '["]' 并且它可以工作,但我不确定它是否仍然适用于/a/b/c/abc.txt
  • @Emma 它的/userfiles/abc.txt

标签: python regex


【解决方案1】:

假设:

1) 你想要的永远是一个txt文件

2) 字符串总是一个 path 包含字符 /

以下模式应该有效:

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)

输出:

/userfiles/abc.txt

Link for reference

【讨论】:

    【解决方案2】:

    这个表达式可能在这里起作用:

    OnUploadCompleted\([0-9]+\s*,\s*\"\/(.+?)\"
    

    我们想要的输出在这个捕获组(.+?)

    Please see the demo for additional explanation.

    测试

    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)))
    

    【讨论】:

    • 我可能是错的,但我的理解是 OP 想要完整路径作为输出(基本上是第一个双引号内的内容),他/她不需要的是 only i> 第二对双引号内的文件名。
    猜你喜欢
    • 2012-03-20
    • 2015-01-22
    • 1970-01-01
    • 2016-07-29
    • 2017-06-18
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    • 2016-02-15
    相关资源
    最近更新 更多