Viki@Stag has asked for the wisdom of the Perl Monks concerning the following question:

/(\s*\d+th\s+\w+\s*)-\1/

iam using the abv pattern for matching text like "5th April - 12th April". But iam not able to match it, shud i change the pattern?

Thanks Monks

Replies are listed 'Best First'.
Re: pattern matching
by GrandFather (Saint) on Nov 22, 2007 at 08:48 UTC

    The problem is most likely the \1, which is not repeating the first capture as I suspect you want. You may want to do something like:

    use strict; use warnings; my $matchDate = qr/(\s*\d+th\s+\w+\s*)/; while (<DATA>) { next unless /$matchDate\s+-\s+$matchDate/; print "Matched: $1 - $2\n"; } __DATA__ 5th April - 12th April

    Prints:

    Matched: 5th April - 12th April

    Perl is environmentally friendly - it saves trees
      Thank u. This worked.

      Thanks to this idea too -> (th|rd|st|nd)
Re: pattern matching
by mwah (Hermit) on Nov 22, 2007 at 10:47 UTC

    GrandFather already identified the problem in your code; in case you'd like to extend your program to other numerals (1,2,3 - as noted by gangabass), there's another variant:

    use strict; use warnings; my $dates = '5th April - 12th April xxxx, ssss, 3rd May - 23th May zzz! 1st June-2nd June, ddd'; my $subexp = qr{ (?:-\s*)? # may be we hit the second term \d+ (?:st|nd|rd|th) # the day \s+\w+\s* # the month }x; my @hits = $dates =~ /$subexp $subexp/xg; print join "\n", @hits;

    Regards

    mwa

      Not sure I'd count '23th May' as a valid date ;-)
      Cheers
      Chris
Re: pattern matching
by Gangabass (Vicar) on Nov 22, 2007 at 09:11 UTC

    Don't forget to include in your pattern 1, 2 and 3 day of each month.