Gyatso has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks ,
Have a question for you regarding regular expressions.
Suppose I have the following string:
Gyatso is a bad monk as bad as bad bad as bad bad bad bad bad.

Say I want a regular expression to:
Match the string starting with Gyatso upto the third 'bad' and not more.

Regular expression I wrote:
^Gyatso.+?bad.+?bad.+?bad

Though above regex matches the requirement but I am not happy at all with this regexp and I am sure there must be a better way.There must be some way of writing a regular expression which should match upto the nth(say 5th or 6th)'bad' in the above expression.What would be the regular expression in that case.

Thanks monks for all your wisdom.

Best Regards,
Gyatso

Replies are listed 'Best First'.
Re: Question on Regular expression
by kennethk (Abbot) on Jul 28, 2009 at 13:48 UTC
    You can do it in a fairly straight forward way using Non capturing groupings combined with {} for Matching repetitions:

    #!/usr/bin/perl use strict; use warnings; my $string = 'Gyatso is a bad monk as bad as bad bad as bad bad bad ba +d bad.'; my $n = 5; print ($string =~ /(^Gyatso(?:.+?bad){$n})/);
Re: Question on Regular expression
by psini (Deacon) on Jul 28, 2009 at 13:47 UTC

    Untested, but I think that /^Gyatso(?:.+?bad){3}/ should work.

    Rule One: "Do not act incautiously when confronting a little bald wrinkly smiling man."