我正在尝试编写一个正则表达式来匹配可选引用的值(有效的引号是"'
和`)。规则是两个引号的出现是一个转义的引号。
这是我想出的正则表达式:
(?P<quote>["'`])?(?P<value>(?(quote)((?!(?P=quote).)|((?=(?P=quote)).){2})*|[^\s;]*))(?(quote)(?P=quote)|)
现在可读(注释表明我认为它做了什么):
(?P<quote>["'`])? #named group Quote (any quoting character?)
(?P<value> #name this group "value", what I am interested in
(?(quote) #if quoted
((?!(?P=quote).)|((?=(?P=quote)).){2})* #see below
#match either anything that is not the quote
#or match 2 quotes
|
[^\s;]* #match anything that is not whitespace or ; (my seperators if there are no quotes)
)
)
(?(quote)(?P=quote)|) #if we had a leeding quote we need to consume a closing quote
它对不带引号的字符串执行良好,带引号的字符串会使其崩溃:
match = re.match(regexValue, line)
File "****/jython2.5.1/Lib/re.py", line 137, in match
return _compile(pattern, flags).match(string)
RuntimeError: maximum recursion depth exceeded
我做错了什么?
编辑:示例输入 => 输出(用于捕获组“值”(所需)
text => text
'text' => text
te xt => te
'te''xt'=> te''xt #quote=' => strreplace("''","'") => desired result: te'xt
'te xt' => te xt
编辑2:在查看它时我注意到一个错误,见下文,但是我相信上面仍然是一个有效的 re +> 它可能是一个 Jython 错误,但它仍然没有做我想要它做的事情:(非常微妙差异,点移出前瞻组
new:(?P<quote>["'`])?(?P<value>(?(quote)((?!(?P=quote)).|((?=(?P=quote)).){2})*|[^\s;]*))(?(quote)(?P=quote)|)
old:(?P<quote>["'`])?(?P<value>(?(quote)((?!(?P=quote).)|((?=(?P=quote)).){2})*|[^\s;]*))(?(quote)(?P=quote)|)