如何使用正则表达式从冒号前的字符串中提取单词并在 python 中从中排除 \n

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

regex demo详情:

  • ^ - 行首
  • [^:-] - 除了 :-
  • 之外的任何字符
  • [^:]* - :
  • 以外的任意 0 个或多个字符
  • ^([^:\n-][^:\n]*): - 捕获除 :- 和换行符之外的任何字符的序列,后跟除 : 和换行符之外的任何 0 个或更多字符一行的开头,并且还匹配紧随其后的 :(这不是组的一部分,因此 re.findall 不会返回)。

看到一个Python demo:

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']