Regex match zero or one time a string

In your edit you mention an unwanted leading space in the result… to check a leading or trailing condition together with your regex without including this to the result you can use lookaround feature of regex.

new Regex(@"(?<=Date )(HH)?:?(MM)?:?(ss)?")

(?<=...) is a lookbehind pattern.

Regex test site with this example.

For input Date HH:MM:ss, it will match both regexes (with or without lookbehind).

But input FooBar HH:MM:ss will still match a simple regex, but the lookbehind will fail here. Lookaround doesn't change the content of the result, but it prevents false matches (e.g., this second input that is not a Date).

Find more information on regex and lookaround here.


(H{2})? matches zero or two H characters.

However, in your case, writing it twice would be more readable:

Regex dateRegex = new Regex(@"\{Date (HH)?:(MM)?:(ss)?\}");

Besides that, make sure there are no functions available for whatever you are trying to do. Parsing dates is pretty common and most programming languages have functions in their standard library - I'd almost bet 1k of my reputation that .NET has such functions, too.

Tags:

C#

Regex