【问题标题】:extract sub-string from long text从长文本中提取子字符串
【发布时间】:2021-11-08 14:27:37
【问题描述】:

我有一个字符串:

string="
(2021-07-04 11:58:43 PM BST)  
---  
le  ) says tosen  

你好,你好

(2021-07-05 12:04:42 AM BST)  
---  
len (Trade ) says to sen  
okay -5 / 0  .



(2021-07-04 11:47:14 PM BST)  
---  
Keun says to
HanSo 
hello 
  
  
  
  
--- 


  
  

(2021-07-05 12:09:41 AM BST)  
---  
len (Trade) says to sen  
yes -5 / 0 TN -- / +2.5  
  
  
---  
  
* * *

Processe | 2021-07-05 12:26:44 AM
BST  
---

"

我只想提取says to之后和timestamp之前的文本。

预期输出为:

text=['yoh Hi yo','sen OK -5 / 0','sen yes -5 / 0 TN -- / +2.5']

我尝试过的:

text=re.findall(r'表示为 (\D+)(',string)

【问题讨论】:

    标签: python-3.x regex


    【解决方案1】:

    says to和括号之间的下一个时间戳之间有数字,所以使用\D+会在有数字时停止匹配。

    相反,您可以在匹配组 1 中的 says to 后捕获所有以下不以 ( 和数字或 --- 开头的行(或使其更具体)

    \bsays to (.*(?:\n(?!\(\d|---).*?)*?)\s*\n(?:\(\d|---)
    

    Regex demo | Python demo

    例如:

    pattern = r"\bsays to (.*(?:\n(?!\(\d|---).*?)*?)\s*\n(?:\(\d|---)"
    text = re.findall(pattern, text)
    print(text)
    

    输出

    ['yohan sen  \n[[:Conversations will be recorded and may be monitored by the participants and\ntheir employers:]] Hi yohan', 'yohan sen  \nokay -5 / 0', 'yohan sen  \nyes -5 / 0 TN -- / +2.5']
    

    【讨论】:

    • 非常感谢。还有一个疑问,因为字符串中的says to 也可能有变化,因为我已经编辑了问题(名称也可以在下一行)。请问在这种情况下如何处理'\n'?
    • @new_learner 你的意思是像这样用单词边界而不是空格吗? \bsays to\b(.*(?:\n(?!\(\d|---).*?)*?)\s*\n(?:\(\d|---)regex101.com/r/2iILa4/1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多