[英]How can i extract words from a string before colon and excluding \n from them in python using regex
我想從字符串中提取冒號 (:) 之前但沒有 \n 字符的單詞
我有以下字符串:
enx002: connected to Wired connection 2
docker0: connected to docker0
virbr0: connected to virbr0
tun0: connected to tun0
我想提取之前的話:
我使用了一個正則表達式:
pattern = '[^:-].*?:\s*'
xx = re.findall(pattern, stringfromabove)
我確實得到了一個字符串列表,正如他們所期望的那樣:最后也是 \n 示例:xx[3] 將是 '\ntun0:'
我想要的只是'tun0'
感謝您的幫助
您可以使用
re.findall(r'^[^:-][^:]*', stringfromabove, re.M)
re.findall(r'^([^:\n-][^:\n]*):', stringfromabove, re.M) # This will make sure there is a `:` on the line and `\n` will make sure the match does not span multiple lines
請參閱正則表達式演示。 詳情:
^
- 行首[^:-]
- 任何字符,但:
和-
[^:]*
- 任何 0 個或多個字符,除了:
^([^:\n-][^:\n]*):
- 捕獲除:
之外的任何字符序列, -
和一個換行符,后跟除:
和換行符之外的任何 0 個或多個字符, 並且還匹配:
之后(它不是組的一部分,因此不會由re.findall
返回)。請參閱Python 演示:
import re
rx = r"^[^:-][^:]*"
text = "enx002: connected to Wired connection 2\ndocker0: connected to docker0\nvirbr0: connected to virbr0\ntun0: connected to tun0"
print( re.findall(rx, text, re.M) )
# => ['enx002', 'docker0', 'virbr0', 'tun0']
print( re.findall(r'^([^:\n-][^:\n]*):', text, re.M) )
# => ['enx002', 'docker0', 'virbr0', 'tun0']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.