Regex format returns empty result - C #

I have a text string and I intend to extract the "date" after ",", i, e, September 1, 2015

Distribution / Stratification Report 10835.0000 Report for the reporting period 228, 1 Sept. 2015

I wrote the regex code below and it returns an empty match.

`Regex regexdate = new Regex(@"\Allocation/bundle\s+\report\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\,\+(\S)+\s+(\S)+\s+(\S)"); // to get dates MatchCollection matchesdate = regexdate.Matches(text); 

Can you talk about what's wrong with the Regex format that I mentioned?

+5
source share
2 answers

\A is an anchor stating the beginning of a line. You must have meant A (\S)+ should be converted to (\S+) . Also, \r is a carriage return matching pattern, remove the backslash again to turn \r into r .

Use

 @"Allocation/bundle\s+report\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\,\s+(\S+)\s+(\S+)\s+(\S+)" 

Watch the regex demo

enter image description here

Note that the last part of the regular expression may be a little more specific to match 1 + digits, then a few letters and then 4 digits: (\S+)\s+(\S+)\s+(\S+) โ†’ (\d+)\s+(\p{L}+)\s+(\d{4})

+5
source

Can you do this without regex? Here is an example using a bit of LINQ help.

 var text = "Allocation/bundle report 10835.0000 Days report step 228, 1 Sep 2015"; var sDate = text.Split(',').Last().Trim(); if (string.IsNullOrEmpty(sDate)) { Console.WriteLine("No date found."); } else { Console.WriteLine(sDate); // Returns "1 Sep 2015" } 
+5
source

Source: https://habr.com/ru/post/1260732/


All Articles