Regex Match all characters until reach character, but also include last match

Viewed 147

I'm trying to find all Color Hex codes using Regex.

I have this string value for example - #FF0000FF#0038FFFF#51FF00FF#F400FFFF and I use this:

#.+?(?=#)

pattern to match all characters until it reaches #, but it stops at the last character, which should be the last match.

I'm kind of new to this Regex stuff. How could I also get the last match?

2 Answers

Your regex does not match the last value because your regex (with the positive lookahead (?=#)) requires a # to appear after an already consumed value, and there is no # at the end of the string.

You may use

#[^#]+

See the regex demo

The [^#] negated character class matches any char but # (+ means 1 or more occurrences) and does not require a # to appear immediately to the right of the currently matched value.

In C#, you may collect all matches using

var result = Regex.Matches(s, @"#[^#]+")
    .Cast<Match>()
    .Select(x => x.Value)
    .ToList();

A more precise pattern you may use is #[A-Fa-f0-9]{8}, it matches a # and then any 8 hex chars, digits or letters from a to f and A to F.

Don't rely upon any characters after the #, match hex characters and it
will work every time.

(?i)#[a-f0-9]+

Related