簡體   English   中英

匹配除特殊模式后的所有內容,除了空格直到下一個字母

[英]Match everything after particular pattern except whitespace till next letter

我有一個像這樣的字符串:

'Medicine Treatment:     Not applicable'

現在,我希望匹配相應的治療方法,但治療前面沒有白色空間。 所以我只想匹配: "Not applicable"而不是" Not applicable"

我很確定它一定是這樣的:

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

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

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

您可以在不使用正則表達式的情況下執行此操作,但可以組合split()strip()函數:

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

輸出:

'Not applicable'

如果你有一個字符串ss.strip()將是字符串的副本,兩邊沒有空格, s.lstrip()只會從左邊刪除空格。

re不支持未知長度的圖案匹配字符串(雖然有可能用的PyPI regex模塊 )。 所以,你不能使用re.search(r'(?<=Medicine Treatment:\\s*).*', txt) (它適用於PyPi regex.search )。

您可以使用捕獲組而不是lookbehind:

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

請參閱Python演示

細節

  • Medicine Treatment: - 文字字符串(作為所需匹配的左手上下文)
  • \\s* - 消耗零個或多個空格字符
  • (.*) - 盡可能多地捕獲除換行符之外的任何0或更多字符的第1組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM