【问题标题】:Specific Python pattern for the string that can help to slice有助于切片的字符串的特定 Python 模式
【发布时间】:2016-04-05 06:27:05
【问题描述】:

我正在寻找可以帮助我分割字符串的模式。字符串是这样的:

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不工作但不属于4个
  5. 这应该是 5 等等...

我希望你已经明白了。

到目前为止,我检查的是我可以使用这个:

import re

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

在遇到单个数字之前效果很好。 我知道 \D 表达式是非数字的,我尝试使用:

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

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

还有很多其他的,但我找不到合适的。

我会很感激你的帮助。

【问题讨论】:

  • 也许这会有所帮助? stackoverflow.com/questions/2260280/…
  • @MikkelBueTellus - 我认为这没有多大帮助,因为这里已经在使用它了。
  • 如果r'\d\. .*?' 工作就好了。其他一切最终看起来都是一种解决方法。

标签: python regex findall


【解决方案1】:

您可以使用否定的前瞻:

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

这匹配一个数字和点,后跟 anything,前提是任何数字后面都没有直接跟点。

演示:

>>> 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 标志。

【讨论】:

    【解决方案2】:

    只是根据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...']

    【讨论】:

      【解决方案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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-02-08
        • 2021-06-08
        • 2022-11-23
        • 2014-07-21
        • 2012-02-15
        • 1970-01-01
        相关资源
        最近更新 更多