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

In PERL, I'm trying to use a regular expression that will replace two digits at the beginning of a string with 'testtext'. There will be instances of strings that have 0, 1, 2, and more digits at the beginning, but I only want to substitute 'testtext' for those strings that have EXACTLY two digits at the beginning. For instance: 1Sallywentthisway --> gets skipped in the replace for having only 1 digit 00tomwentthatway --> 00 is replaced with testtext 123joestayedstill --> gets skipped in the replace for having over 2 digits 11Billisgone --> 11 is replaced with testtext This line of PERL code is not enough: $segment =~ s/^\d{2}/testtext/; That code will change the 123joestayedstill to testtext3joestayedstill Where is my regular expression out of joint? THANK YOU!

Replies are listed 'Best First'.
Re: Regular Expression Question
by kennethk (Abbot) on Dec 18, 2013 at 17:34 UTC
    Please read How do I post a question effectively?. In particular, please wrap code, input and output in <code> tags.

    There are multiple ways to achieve your desired result, but I would do it using Look Around Assertions. In your case, your code might look like:

    $segment =~ s/^\d{2}(?!\d)/testtext/;
    which YAPE::Regex::Explain describes as
    NODE EXPLANATION ---------------------------------------------------------------------- ^ the beginning of the string ---------------------------------------------------------------------- \d{2} digits (0-9) (2 times) ---------------------------------------------------------------------- (?! look ahead to see if there is not: ---------------------------------------------------------------------- \d digits (0-9) ---------------------------------------------------------------------- ) end of look-ahead ----------------------------------------------------------------------

    Some side notes:

    • The language is Perl, the interpreter is perl; there is no 'PERL' (excluding when I get very excited about Perl. And who doesn't?)
    • If this is class-work, please qualify it as such. We are all happy to help beginners learn and help you debug, but Monks doing work for you won't help you learn. It also tends to raise ire in the Monastery.

    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.