I have a string with 3 dates in it like this:
XXXXX_20160207_20180208_XXXXXXX_20190408T160742_xxxxx
I want to select the 2nd date in the string, the 20180208
one.
Is there away to do this purely in the regex
, with have to resort to pulling out the 2 match in code. I'm using C#
if that matters.
Thanks for any help.
You can use System.Text.RegularExpressions.Regex
See the following example
You could use the regular expression
to save the 2nd date to capture group 1.
Demo
Naturally, for
n > 2
, replace{1}
with{n-1}
to obtain the nth date. To obtain the 1st date useDemo
The C#'s regex engine performs the following operations.
The important thing to note is that
.*?
, followed by\d{8}
, because it is lazy, will gobble up as many characters as it can until the next 8 characters are digits (and are not preceded or followed by a digit. For example, in the stringcapture group 1 in
(.*?)_\d{8}_
will contain"_1234abcd_efghi_123456789"
.You could use
And take the first group, see a demo on regex101.com.
Broken down, this says
C# demo:
Try this one