3

代码如下:

#coding=utf-8

import re

str = "The output is\n"
str += "1) python\n"
str += "A dynamic language\n"
str += "easy to learn\n"
str += "2) C++\n"
str += "difficult to learn\n"
str += "3244) PHP\n"
str += "eay to learn\n"


pattern = r'^[1-9]+\) .*'
print re.findall(pattern,str,re.M)

输出是

['1) python', '2) C++', '3244) PHP']

但是,我想像这样拆分它:

['1) python\n'A dynamic language\n easy to learn\n'  2) C++\n difficult to learn\n', '3244) PHP\n easy to learn\n']

也就是说,忽略不以“number)”开头的第一行,当遇到一个数字时,直到下一行以“number)”开头的以下行被认为是同一组。我应该如何重写模式?

4

3 回答 3

3
>>> import re
>>> strs = 'The output is\n1) python\nA dynamic language\neasy to learn\n2) C++\ndifficult to learn\n3244) PHP\neay to learn\n'
>>> re.findall(r'\d+\)\s[^\d]+',strs)
['1) python\nA dynamic language\neasy to learn\n',
'2) C++\ndifficult to learn\n',
'3244) PHP\neay to learn\n']
于 2013-06-19T14:35:50.577 回答
2

您可以使用它,允许数字但后面不跟右括号:

re.findall(r'\d+\)\s(?:\D+|\d+(?!\d*\)))*',str)
于 2013-06-19T14:39:01.357 回答
1

您需要将用于空格的 python 正则表达式添加到您的模式中以说明换行符。

尝试这个:

regex = r"[1-9]+\) .*\s.*"

\s 是任何空格的正则表达式

于 2013-06-19T14:35:39.363 回答