python - 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'))
解决方案
在您提供的示例中,我们可以通过稍微更改您提供的 Regex 来获得该分组。
def getvar(string, variable):
return re.findall('var ' + variable + ' = (.*);', string)[0]
这将返回"hello; this should be included"
虽然重要的是要记住,如果您提供的字符串找不到匹配项,此方法将失败。
推荐阅读
- javascript - React 需要处理一些 if 条件
- apache-kafka - kafka 和 schema 注册表如何共享 KafkaProperties?(提供了“basic.auth.user.info”,但不是已知配置。)
- spring - @WebMvcTest vs @ContextConfiguration when testing WebSocket controllers
- apache - htaccess – FALSE If statement still runs
- json - How to write a sentence into JSON file in Qt not necessarily in JSON format?
- python - ModuleNotFoundError: No module named 'numpy.testing.nosetester' AND PermissionError: [WinError 5] Access is denied
- c - How to emit debug information using llvm ir in Clang?
- c# - Filling DataTable column by column C#
- json - Passing X-Authentication via CURL on command line
- python - What is the correct way to reproject a raster from a CRS to another using Python?