I wanted to extract the date pattern "mm/dd/yyyy" from a string, for example, given the string:
"The quick brown fox on 4/26/2018 decided to jump over the moon"
I wanted to extract this date pattern from any string in C#. In starting out I used:
https://regex101.com/r/yG2zN1/1
Using the pcre (PHP) flavor I came up with the following and it seemed to work well for this date format in any sentence:
\d{1,2}\/\d{1,2}\/\d{4}\b
However when I put this in my C# code it would not work:
Regex rx = new Regex(@"\d{1,2}\/\d{1,2}\/\d{4}\b");
MatchCollection mc = rx.Matches(myTestString); //get mm/dd/yyyy
string date = mc[0].Value;
mc comes out false? No match?
So I went over to a couple Dot NET Regex test sites and tried http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx
\d{1,2}\/\d{1,2}\/\d{4}\b - it fails on those sites also for my test string above.
My question is why does "\d{1,2}\/\d{1,2}\/\d{4}\b" work on the PHP regex to extract the date of format mm/dd/yyyy from any string but it does not work with C# regex as shown above?
Just wanted to clarify that for the date pattern mm/dd/yyyy in a string the regex pattern -
@"\d{1,2}/\d{1,2}/\d{4}\b"
does work in both Dot NET C# and at https://regex101.com/r/yG2zN1/1. What I was doing wrong at https://regex101.com/r/yG2zN1/1 was I was not putting the "@" before the regex string this made it so that I had to use the escape char . Thanks to Wiktor Stribizew I was able to go back and revisit this.
In addition in my C# code I had a test string that was bad it was a copy and past string and must have had some weird control characters in it and that was the reason that regex pattern @"\d{1,2}/\d{1,2}/\d{4}\b" was not working. I went back to my code and deleted the original test string and retyped it and now @"\d{1,2}/\d{1,2}/\d{4}\b" works to extract the date pattern mm/dd/yyyy from any string it is embedded in. Again I have to give credit and thanks to Wiktor Stribizew for his help on solving this issue.
Note: my string was coming from the windows 7 embedded system event log ID 6008 event.message for some reason there is some type of invisible characters / non printable characters in that string ultimately I had to use the following regex on the string to clean it: cleanString = Regex.Replace(message, @"\p{C}+", string.Empty);