我是Python中正则表达式的基本用户,需要一些专家建议 使用正则表达式解决问题。
我正在尝试使用以下一组规则从字符串中提取一些信息。
作为一种解决方案,如果以某种方式允许在字符集[]中定义和使用特殊类型的字符,那将很容易。
例如:
re.compile("""\$\((\w*)
[(any characters except ' and " [if used singly not in pairs] )
(' and " [if used singly not in pairs] are allowed only if escaped using a \)
( even ) if enclosed within '' or "")
]\)""", re.VERBOSE)
一些测试:
是否可以在Python中执行此类操作,或者我对解决方案的处理方法不是Pythonic? 还建议,如果有更好的解决方案。
感谢
答案 0 :(得分:1)
这个似乎按照你的要求行事:
^\$\((\w(?:\w|[^)\\"']|"[^"]*"|'[^']*'|\\"|\\')*)\)
击穿:
^ # start of string
\$\( # "$("
( # start group 1
\w # a word character
(?: # start non-capturing group, one of:
\w # a word character
| # or
[^)\\"'] # anything except ")" and special characters
| # or
"[^"]*" # a double-quoted section
| # or
'[^']*' # a single-quoted section
| # or
\\" # a backslash-escaped double quote
| # or
\\' # a backslash-escaped single quote
)* # end group, repeat
) # end group 1
\) # ")"
它与您的示例要求匹配。
缺点:
\w
。熟悉\w
匹配的内容,并在必要时使用更具体的内容。测试:
regex = re.compile("^\$\((\w(?:\w|[^)\\\"']|\"[^\"]*\"|'[^']*'|\\\"|\\')*)\)")
string = "$(listInput:J=join\'with) tail"
r = regex.search(string)
r.groups()
# -> (u"listInput:J=join\\'with",)
regex.findall(string)
# -> [u"listInput:J=join\\'with"]