下面是我对regex的输入和结果:
temp2 = '(LEFT-WALL)(who)(is.v)(the)(di(rect)or.n)(of)(Inceptio)(RIGHT-WALL)'
print regex.findall(r'\([^\)\(]*+(?:(?R)[^\)\(]*)*+\)', temp2)
结果:
['(LEFT-WALL)', '(who)', '(is.v)', '(the)', '(di(rect)or.n)', '(of)', '(Inceptio)', '(RIGHT-WALL)']
我想要这样的结果:
['LEFT-WALL', 'who', 'is.v', 'the', 'di(rect)or.n', 'of', 'Inceptio', 'RIGHT-WALL']
正则表达式有变化吗
我觉得您提供的示例字符串不需要任何正则表达式:
sample program的输出:
作为一种不使用regex的替代方法,您可以使用
str.split()
和str.strip()
方法来完成这项工作:或者对于regex,您可以在regex中使用look-around:
注意逻辑很简单,您只需要匹配开括号
(
和紧跟开括号)(
的闭括号之间的字符串您需要匹配
(
和)(
之间的字符串,或者)(
和)
之间的字符串。这样就避免了在'(di(rect)or.n)'
中匹配像'(rect)'
这样的字符串。您可以通过使用lookaround assertions来实现这一点,因为它们不使用所搜索的字符串前瞻性断言:
积极的回顾断言:
在下面的代码中,我使用
re.VERBOSE
标志使其更具可读性相关问题 更多 >
编程相关推荐