带转义单引号的单引号字符串上的 Python 正则表达式

标签 python regex ply

假设我们有一些像这样的输入(这是一个例子,无论它是否有意义):

data = "(((column_1 + 7.45) * 3) <>    column_2 - ('string\'1' / 2))"

嗯,我需要使用 Python re 模块来匹配一个以 ' 开头和结尾的字符串,并且可能包含转义的单引号,如上面的示例。所以结果应该是string\'1。我们怎样才能实现它呢?

编辑:我正在使用 PLY 库,用法应该是

def t_leftOperand_arithmetic_rightOperand_STRING(self, t):
    r'<regex>'
    t.lexer.pop_state()
    return t

最佳答案

我相信你也必须解释被逃脱的情况。

为此,您需要 '[^'\\]*(?:\\[\S\s][^'\\]*)*'

<小时/>

输入

'''Set 1 - this
is another
mul\'tiline
string'''
'''Set 2 - this
is' a\\nother
mul\'''tiline
st''ring'''

Benchmark:

Regex1:   '[^'\\]*(?:\\[\S\s][^'\\]*)*'
Options:  < none >
Completed iterations:   400  /  400     ( x 1000 )
Matches found per iteration:   9
Elapsed Time:    5.00 s,   4995.27 ms,   4995267 µs


Regex2:   '(?:[^'\\]|\\.)*'
Options:  < s >
Completed iterations:   400  /  400     ( x 1000 )
Matches found per iteration:   9
Elapsed Time:    7.00 s,   7000.68 ms,   7000680 µs

额外的正则表达式(仅用于测试。正如 @ridgerunner 所说,这可能导致回溯问题)

Regex2:   '(?:[^'\\]+|\\.)*'
Options:  < s >
Completed iterations:   400  /  400     ( x 1000 )
Matches found per iteration:   9
Elapsed Time:    5.45 s,   5449.72 ms,   5449716 µs

关于带转义单引号的单引号字符串上的 Python 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35397208/

相关文章:

python - 在 matplotlib 中迭代添加总数未知的子图

Javascript:将非表达式简化为捕获组的正则表达式

javascript - 正则表达式替换完全匹配的字符串

python - 在 ply 的正则表达式中匹配 unicode

python - 如何考虑 '|' 创建抽象语法树? (层/Yacc)

python - python 中的数学 - 将数据文件转换为矩阵

python - 如何对已排序的 pandas.Series 进行分组?

python - 在获取和存储用户输入时如何不覆盖字典的值? (Python)

html - 正则表达式从 html 中删除行注释

python - PLY:需要帮助理解 LALR 解析器如何解析给定语法的输入