我试图使用正则表达式模式在Python中拆分字符串,但它无法正常工作。
示例文字:
"The quick {brown fox} jumped over the {lazy} dog"
代码:
"The quick {brown fox} jumped over the {lazy} dog".split(r'({.*?}))
我正在使用捕获组,以便拆分分隔符保留在数组中。
期望的结果:
['The quick', '{brown fox}', 'jumped over the', '{lazy}', 'dog']
实际结果:
['The quick {brown fox} jumped over the {lazy} dog']
正如您所看到的,显然没有匹配,因为它没有拆分字符串。任何人都可以让我知道我哪里出错了吗?感谢。
答案 0 :(得分:1)
你正在调用字符串的split方法,而不是re's
>>> re.split(r'({.*?})', "The quick {brown fox} jumped over the {lazy} dog")
['The quick ', '{brown fox}', ' jumped over the ', '{lazy}', ' dog']