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?
An empty regular expression matches everything.
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).
Java static code analysis: Repeated patterns in regular expressions should not match the empty string.
\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.
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
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})
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With