Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex format returns empty result - C#

Tags:

c#

regex

I have below text line and I intend to extract the "date" after the ",", i,e, 1 Sep 2015

Allocation/bundle report 10835.0000 Days report step 228, 1 Sep 2015

I wrote the below regex code and it returns empty in the 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 advice about what's wrong with the Regex format that I mentioned?

like image 516
user7157732 Avatar asked Dec 02 '16 19:12

user7157732


People also ask

What does an empty regex match?

An empty regular expression matches everything.

What does \+ mean in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

Does regex match empty string?

Java static code analysis: Repeated patterns in regular expressions should not match the empty string.

How do you match a space in regex?

\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.


2 Answers

The \A is an anchor asserting the start of string. You must have meant A. (\S)+ must be turned into (\S+). Also, \r is a carriage return matching pattern, again remove the backslash 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+)"

See the regex demo

enter image description here

Note that the last part of the regex may be made a bit more specific to match 1+ digits, then some letters and then 4 digits: (\S+)\s+(\S+)\s+(\S+) -> (\d+)\s+(\p{L}+)\s+(\d{4})

like image 165
Wiktor Stribiżew Avatar answered Oct 04 '22 18:10

Wiktor Stribiżew


Can you do it without Regex? Here's an example using a bit of help from LINQ.

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"
}
like image 39
Noppadet Avatar answered Oct 04 '22 19:10

Noppadet