python - 在 Python 中使用正则表达式从字符串中的源代码中提取字符串常量

标签 python regex lexical-analysis

<分区>

如何从字符串中的源代码中获取字符串常量?

例如,这是我要处理的源代码:

var v = "this is string constant + some numbers and \" is also included "

我无法将所有内容都放在引号内。通过使用此正则表达式:"(.*?)"

我无法获取 varv= 或除字符串字符以外的任何其他内容。

最佳答案

使用 lookbehind,确保 "前面没有\

import re

data = 'var v = "this is string constant + some numbers and \" is also included "\r\nvar v = "and another \"line\" "'
matches = re.findall( r'= "(.*(?<!\\))"', data, re.I | re.M)
print(matches)

输出:

['this is string constant + some numbers and " is also included ', 'and another "line" ']

关于python - 在 Python 中使用正则表达式从字符串中的源代码中提取字符串常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16001544/

相关文章:

python - 在 Keras 中训练和保存非常大的模型

python argparse 处理任意数字选项(如 HEAD(1))

python - 如何从 Python 中的函数中去除装饰器

java - 如何从字符串中转义\s(空格字符)?

regex - 防弹文字

c++ - 在哪里可以获得能够报告 C 或 C++ 中的 for 循环错误的词法分析器?

python - 想要从网站获取信息,但使用Python显示 "250 forbidden"

java - 检查字符串是否匹配特定的正则表达式

algorithm - 如何识别文本中的一组关键词

java - 什么会导致 Java 编译器在解析注释时失败?