Reputation: 127
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
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 spaceFor 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.Upvotes: 0
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 colonshttps://regex101.com/r/LMQrb7/1
To access the word you're looking for, use group 1.
Upvotes: 0
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