Search code examples
regexregex-groupregex-greedy

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.


Solution

  • 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