在python中,我想使用正则表达式在字符串中查找嵌入的项列表
我希望能够拆分以下字符串:在python中,我想使用正则表达式在字符串中查找嵌入的项列表,python,regex,string,split,Python,Regex,String,Split,我希望能够拆分以下字符串: "This is a string with an embedded list. 1. My first list item. 2. My second item. a. My first sub-item. b. My second sub-item. 3. My last list item." 我想将其拆分为: "This is a string with an embedded list." "1. My first list item." "2.
"This is a string with an embedded list. 1. My first list item. 2. My second item. a. My first sub-item. b. My second sub-item. 3. My last list item."
我想将其拆分为:
"This is a string with an embedded list."
"1. My first list item."
"2. My second item."
"a. My first sub-item."
"b. My second sub-item."
"3. My last list item."
我不能保证每个嵌入的列表项之前总是有两个空格,但它至少有一个空格,或者它将启动字符串。此外,我不能保证嵌入列表中的第一个单词总是大写。最后,字符串中的数字和字母部分可能会以数字的形式进入青少年,因此有可能获得一个以“10”开头的条目。如果没有嵌入列表,我希望它只返回原始字符串,不需要拆分
关于识别嵌入列表项的规则,以下是我的一些想法:
虽然这不是一组详尽的条件,但我认为它会找到大量的嵌入列表。您可以使用这个正则表达式进行拆分,它会查找一些空格,后跟数字和句点或字母和句点:
\s+(?=(?:\d+|[a-z])\.)
在python中(注意使用re.I
标志来匹配大写和小写字母):
输出:
[
'This is a string with an embedded list.',
'1. My first list item.',
'2. My second item.',
'a. My first sub-item.',
'b. My second sub-item.',
'3. My last list item.'
]
作为一个人,您如何识别列表项?它是否类似于“任何简短的(你能
split()
使用一些额外的规则吗?或者你需要正则表达式吗?@B,如果可以解决这个问题,我愿意使用split()。@Grismar,我已经添加了一些关于如何识别嵌入列表项的想法。它不会详尽无遗,但会很好地找到我想要的东西。
[
'This is a string with an embedded list.',
'1. My first list item.',
'2. My second item.',
'a. My first sub-item.',
'b. My second sub-item.',
'3. My last list item.'
]