可以帮助sli的字符串的特定Python模式

2024-04-25 19:26:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我在找有助于切丝的图案。字符串是这样的:

text = '1. first slice 2. second slice 3. slice number 3 4. the next one
 5 that will not work but belong to no four 5. and this should be 5 and
 so one...'

我想得到这个:

  1. 第一片
  2. 第二片
  3. 切片编号3
  4. 下一个将不起作用,但属于第四
  5. 这个应该是5,以此类推。。。你知道吗

我希望你有这个想法。你知道吗

到目前为止,我所研究的是我可以使用这个:

import re

parts = re.findall("\d\\. \D+", text)

在遇到一个数字之前,它一直工作得很好。 我知道\D表达式是非数字的,我尝试使用:

parts = re.findall("\d\\. .+,text)

或者

parts = re.findall("(\d\\.).*,text)

还有很多,但我找不到合适的。你知道吗

我将感谢你的帮助。你知道吗


Tags: andthe字符串textrenumberslice数字
3条回答

这应该管用

( #First group to be captured
   \d+\..*? #Match digit(s) followed by decimal and make it non-greedy
)
(?=  #Lookahed
   \d+\. #Check if what follows is digit(s) followed by decimal
   | #or
   $ #End of string
)

Regex Demo

正则表达式分解

(\d+\..*?)(?=\d+\.|$)

Python代码

import re
text = '1. first slice 2. second slice 3. slice number 3 4. the next one 5 that will not work but belong to no four 5. and this should be 5 and so one...'
parts = re.findall(r"(\d+\..*?)(?=\d+\.|$)", text)
print(parts)

Ideone Demo

你可以使用消极的前瞻:

parts = re.findall(r"\d\. (?:\D+|\d(?!\.))*", text)

它匹配一个数字和一个点,后跟任何东西,前提是任何数字后面都不直接跟一个点。你知道吗

演示:

>>> import re
>>> text = '1. first slice 2. second slice 3. slice number 3 4. the next one 5 that will not work but belong to no four 5. and this should be 5 and so one...'
>>> re.findall(r"\d\. (?:\D+|\d(?!\.))*", text)
['1. first slice ', '2. second slice ', '3. slice number 3 ', '4. the next one 5 that will not work but belong to no four ', '5. and this should be 5 and so one...']

在线演示https://regex101.com/r/kF9jT1/1;为了模拟re.findall()行为,我添加了一个额外的(..)g标志。你知道吗

只是基于lookahead进行拆分。你知道吗

 x="""1. first slice 2. second slice 3. slice number 3 4. the next one
5 that will not work but belong to no four 5. and this should be 5 and
so one..."""
print re.split(r"\s(?=\d+\.\s)",x)

输出:['1. first slice', '2. second slice', '3. slice number 3', '4. the next one\n 5 that will not work but belong to no four', '5. and this should be 5 and\n so one...']

相关问题 更多 >