Home > Enterprise >  Extract content after colon if only one : exists in string
Extract content after colon if only one : exists in string

Time:09-13

I want to extract the content after the :, but there can be only one :.

Examples:

foo:bar             # match, extract 'bar'
foo:123             # match, extract '123'

foo:bar:123         # do not match

So that last example should not match because it has multiple :.

I tried a negative lookbehind ^. (?<!:):(. )$ but that nonetheless matches and extracts from that last example.

Here's a demo.

CodePudding user response:

Try (regex101):

^[^:] :([^:] )$

This will match only lines with one : and get the string after the :

CodePudding user response:

In C# you could also make use of lookbehind with an infinite quantifier to get a match only:

(?<=^[^:]*:)[^:] $

Explanation

  • (?<= Positive lookbehind, assert what is to the left is
    • ^ Assert the start of the string
    • [^:]*: Match optional chars other than : followed by matching the :
  • ) Close the lookbehind
  • [^:] Match 1 chars other than :
  • $ End of string

See a .NET regex demo.

If you don't want to cross newlines:

(?<=^[^:\r\n]*:)[^:\r\n] $
  • Related