Vishal
Vishal

Reputation: 127

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

I have to do Full Match for a word which comes after the last colon and between spaces. e.g. In below Sentence

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

Here I have to do full match for ABCdef. ([^:.*\s]+$) returns Down, ([^:]+$) returns ' ABCdef Service is Down' as full match. However I am looking for ABCdef as full match.

Upvotes: 1

Views: 1597

Answers (3)

The fourth bird
The fourth bird

Reputation: 163577

You can match until the last occurrence of :, then match a spaces and capture 1+ non whitespace chars in group 1.

^.*: +(\S+)

Explanation

  • ^ Start of string
  • .*: + Match any char except a newline as much as possible followed by 1 or more spaces
  • (\S+) capture group 1, match 1+ times a non whitespace char followed by a space

Regex demo

For a match only, you might use a positive lookarounds:

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

Explanation

  • (?<=: ) Positive lookbehind, assert what is directly to the left is `:
  • [^\s:]+ Match 1+ times any char except a whitespace char or :
  • (?=[^\r\n:]*$) Positive lookahead, assert what is at the right it 0+ times any char except a newline or : and assert the end of the string.

Regex demo

Upvotes: 0

Jeffery Thomas
Jeffery Thomas

Reputation: 42598

I think the simplest [ ]*([^: ]*)[^:]*$

  • [ ]*: any amount of spaces
  • ([^: ]*): a group with the target non-space word with no colons
  • [^:]*$: the rest of the line without colons

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


To access the word you're looking for, use group 1.

Upvotes: 0

Enigmativity
Enigmativity

Reputation: 117154

Using C#, this works:

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);

I get:

ABCdef

Upvotes: 0

Related Questions