首页 > 解决方案 > Python regex 在第一个分号后切断 javascript 变量

问题描述

如何获取变量的全部内容,以便 getvar() 返回"hello; this should be included"而不是"hello?我将如何更改正则表达式模式以使其工作?

import re

def getvar(string, variable):
    return re.findall('var ' + variable + ' = (.*?);', string)[0]

print(getvar("""<script>var first_variable = "hello; this should be included";</script>""", 'first_variable'))

标签: pythonre

解决方案


在您提供的示例中,我们可以通过稍微更改您提供的 Regex 来获得该分组。

def getvar(string, variable):
return re.findall('var ' + variable + ' = (.*);', string)[0]

这将返回"hello; this should be included" 虽然重要的是要记住,如果您提供的字符串找不到匹配项,此方法将失败。


推荐阅读