簡體   English   中英

通過正則表達式在符號之間查找值,其中符號可能是值的一部分

[英]Finding values between symbols by regex where symbol might be part of value

我正在嘗試從符號之間提取值的字符串,但是符號或定界符也恰好是字符串的一部分。

假設下面的字符串:

message =': :1:1st message:2a:2nd message:x:this is where it fails status: fail :3:3rd message'

和預期的結果:

['1st message','2nd message','this is where it fails status: fail','3rd message']

當前代碼和結果:

import re
def trans(text):
    text = text+':'
    tag = re.findall(r':(.*?):',text)
    return [i for i in tag if not i.isspace()]

trans(message)

>>['1st message', '2nd message', 'this is where it fails status', '3']

是否知道如何構成正則表達式以包括將'status: fail '作為結果一部分的模式?

嘗試使用否定的前瞻r'[^\\s]:(.*?):(?!\\s)

結果:

 ['1st message', '2nd message', 'this is where it fails status: fail ', '3rd message'] 
  • [^\\s]不匹配冒號,冒號后跟空白字符,因此它可以修復3rd message
  • :(?!\\s)用來匹配冒號而不是空格字符,因此它可以修復status: fail
  • 換句話說,我添加的兩個部分都在要匹配的子字符串周圍創建了一個空白,該空白不能包含在冒號之前或之后的冒號。

您可以使用

re.findall(r'(?<=:\S:).+?(?=\s*:.:|$)', message)

在冒號(或字符串的開頭)內向后尋找一個字符,然后匹配並延遲重復任何字符,直到超前字符在冒號(或字符串的末尾)內看到另一個字符。

輸出:

['1st message', '2nd message', 'this is where it fails status: fail', '3rd message']

嘗試Regex:: :\\d+:\\K.*?(?=:\\d+|$)

演示

暫無
暫無

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

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