我将尝试编写一个正则表达式来匹配可选的带引号的值(有效的引号是
"'
和`)。
规则是两个引号的出现是转义引号。
以下是我想到的正则表达式:(?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
我哪里做错了?
编辑:示例输入 => 输出(捕获组“value”(期望)
text => text
'text' => text
te xt => te
'te''xt'=> te''xt #quote=' => strreplace("''","'") => desired result: te'xt
'te xt' => te xt
编辑2: 在查看时我注意到了一个错误,见下文,但我认为上面的仍然是有效的re +>它可能是Jython的一个bug,但它仍然不能做我想要做的事情:(非常微小的差异,点移出了前瞻组
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)|)
|
运算符?例如:"\".*?\"|'.*?'"
。 - Joel Cornett