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

Python regular expression on single quoted string with escaped single quotes

假设我们有这样的输入(这是一个例子,不管它是否有意义):

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