[英]Pymongo finding all Mongo records where value is between two mongo index values
[英]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.