【发布时间】:2015-01-15 07:36:15
【问题描述】:
我是 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)
一些测试:
- this $(listInput) tail -> listInput
- 这个 $(listInput:DS) 尾部 -> listInput:DS
- 这个 $(listInput:J=") ":S=.o) 尾巴 -> listInput:J=") ":S=.o
- this $(listInput:J=join\'with) tail -> listInput:J=join'with
是否可以在 Python 中做这样的事情,或者我对解决方案的方法不是 Pythonic ? 还建议,如果有更好的解决方案。
谢谢
【问题讨论】:
标签: python regex python-2.6