正则表达式在没有 space 且完全匹配的情况下提取最后一个冒号后的第一个单词

Regex to extract first word after last colon without space and with full match

我必须对最后一个冒号之后和空格之间的单词进行 完全匹配。例如在下面的句子

XYZ Cloud : ABC : Windows : Non Prod : Silver : ABC123XYZ : ABCdef Service is Down

这里我必须对 ABCdef 进行完全匹配。 ([^:.*\s]+$) returns 宕机, ([^:]+$) returns 'ABCdef 服务宕机' 已满比赛。但是我正在寻找 ABCdef 作为完全匹配项。

您可以匹配到最后一次出现 :,然后匹配 spaces 并在第 1 组中捕获 1+ 个非白色 space 字符。

^.*: +(\S+)

说明

  • ^ 字符串开头
  • .*: + 尽可能匹配除换行符外的任何字符,后跟 1 个或多个 spaces
  • (\S+) 捕获 组 1,匹配 1+ 次非白色 space 字符后跟 space

Regex demo

仅对于匹配,您可以使用正面环视:

(?<=: )[^\s:]+(?=[^\r\n:]*$)

说明

  • (?<=: ) 正面回顾,断言直接在左边的是 `:
  • [^\s:]+ 匹配任何字符 1 次以上,白色 space 字符或 :
  • 除外
  • (?=[^\r\n:]*$) 正面前瞻,断言右边的内容是除换行符或 : 之外的任何字符的 0+ 次,并断言字符串的结尾。

Regex demo

使用 C#,这有效:

var text = @"XYZ Cloud : ABC : Windows : Non Prod : Silver : ABC123XYZ : ABCdef Service is Down";
var regex = new Regex(@":(?!.*:)\s(.+?)\s.*$");

Console.WriteLine(regex.Match(text).Groups[1].Value);

我得到:

ABCdef

我觉得最简单[ ]*([^: ]*)[^:]*$

  • [ ]*:任意数量的 spaces
  • ([^: ]*): 一组目标非space单词没有冒号
  • [^:]*$: 没有冒号的行的其余部分

https://regex101.com/r/LMQrb7/1


要访问您要查找的词,请使用组 1。