匹配在特定模式之后的所有内容,直到下一个非空格符为止

2024-09-22 20:20:57 发布

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

我有这样一根线:

'Medicine Treatment:     Not applicable'

现在,我想匹配相应的治疗,但治疗前没有空格。 所以我只想匹配:"Not applicable" 而不是" Not applicable"

我很肯定是这样的:

(?<=Medicine Treatment:)[^\s].*

(?<=Medicine Treatment:)\S.*

(?<=Medicine Treatment:).*只返回我不想要的:" Not applicable"


Tags: not空格applicabletreatmentmedicine
3条回答

Python re不支持匹配未知长度字符串的模式(尽管PyPi ^{} module也可以)。因此,您不能使用re.search(r'(?<=Medicine Treatment:\s*).*', txt)(它可以与PyPi regex.search一起使用)

您可以使用捕获组而不是查找组:

import re
s = 'Medicine Treatment:     Not applicable'
m = re.search(r'Medicine Treatment:\s*(.*)', s)
if m:
    print(m.group(1)) # => Not applicable

参见Python demo

细节

  • Medicine Treatment:-文本字符串(用作所需匹配的左侧上下文)
  • \s*-使用零个或多个空格字符
  • (.*)-尽可能多地将除换行符以外的任何0个或更多字符捕获到组1中

您可以不使用regex,而是通过组合split()strip()函数来实现这一点:

s = 'Medicine Treatment:     Not applicable'
s.split('Medicine Treatment:')[1].strip()

输出:

'Not applicable'

如果您有一个字符串ss.strip()将是该字符串的副本,并且s.lstrip()将只删除左边的空白

相关问题 更多 >