user2763995
user2763995

Reputation: 21

Nested regular expressions

I was trying to write a regular expression that matches and captures both the full date, as well as the year of the date.

Example

TEXT: JAN 2013
CAPTURE: JAN 2013, 2013

I tried to use:

[a-z]{3}\s(\d{4},*){2}

But this one doesn't work. If anyone could help.

Upvotes: 0

Views: 86

Answers (2)

Number47
Number47

Reputation: 493

Code in C# for what you wanted (according to comments).

For references you may look MSDN - Regular Expression Language - Quick Reference, here http://msdn.microsoft.com/en-us/library/az24scfc.aspx

Regex r = new Regex(@"\A([a-z]{3}\s+(\d{4}))\Z",
                    RegexOptions.IgnoreCase);

MatchCollection match = r.Matches(text);
if (match.Count == 1)
{
     GroupCollection captures = match[0].Groups;
     String theCaptureYouWanted = captures[1] + ", " + captures[2];
     ...

Upvotes: 0

krisku
krisku

Reputation: 3993

The following regexp gives you two capture groups:

([A-Z]{3}\s(\d{4}))

where the first will contain "JAN 2013" and the second "2013".

Example in Perl:

$text = "JAN 2013";
@m = $text =~ /([A-Z]{3}\s(\d{4}))/;
print "First capture: $m[0]\n";
print "Second capture: $m[1]\n";

Output:

First capture: JAN 2013
Second capture: 2013

Upvotes: 1

Related Questions