Link to home
Start Free TrialLog in
Avatar of ltpitt
ltpitt

asked on

How to prepend a string to a matched string using regex and substitution in Perl

Hi all!

I have many strings, I am looking for those beginning with:
4.2

If I find such a string I would like to prepend to it another string.

So if my parser founds:
test4.2testtest does nothing

If it founds:
4.2testtestanything

It will change it to:
prependedtext4.2testtestanything


I think that basic string substitution would be something like (example is clearly wrong):

sub Test{
        my $test = $_[0];
        $test =~s/^(4.2)/prependedtext/g;
        $test;
}

Thanks for your help!
ASKER CERTIFIED SOLUTION
Avatar of wilcoxon
wilcoxon
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ltpitt
ltpitt

ASKER

This is what I suspected!

Thanks for your help :)

So, just to take something away, $1 means... The whole string?
And $2, $3 and so on?

Thanks again :)
Avatar of ltpitt

ASKER

Worked perfectly
$1 means that first matched text.

$test =~s/^(4.2)/prependedtext$1/g;

means:
1) check if $test starts with 4.2 (do nothing else if it doesn't)
2) replace 4.2 with prependedtext followed by the first captured text (4.2 in this case)
3) leave the rest of the string alone

The g flag shouldn't do anything in this case because you are anchoring the match to the start of the string.

You could also replace the substitution with something like:
$test = 'prependedtext' . $test if ($test =~ m{^4.2});

Open in new window

Avatar of ltpitt

ASKER

Thanks for the extra explanation: super clear and useful!

:)