【问题标题】:Extracting string constant from source code in a string using regular expressions in Python [closed]使用Python中的正则表达式从字符串中的源代码中提取字符串常量[关闭]
【发布时间】:2013-04-14 16:44:47
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • Python 不使用“var”。
  • 你的问题没有多大意义——你到底想完成什么?
  • 看起来您正在尝试使用 Python 解析其他一些编程语言。不要使用正则表达式执行此操作;只会让人心痛。使用适当的解析器。
  • 正则表达式非常适合这个。语言解析器是使用正则表达式构建的,至少在部分工作中,这是一个。

标签: python regex lexical-analysis


【解决方案1】:

使用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" ']

【讨论】:

    【解决方案2】:

    您需要匹配一个开引号,然后是任何转义字符或普通字符(引号和反斜杠除外),然后是右引号:

    "(?:\\.|[^"\\])*"
    

    【讨论】:

    • 是的,正要写这个。完全解析文本和提取只是其中的一些位是有区别的。
    【解决方案3】:

    要获取引号内的所有内容,您可以尝试以下操作: "\".+?\""re.findall()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-17
      • 1970-01-01
      • 2014-08-25
      • 2010-10-14
      • 2012-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多