-1

How can I do a global search and replace on a string of numbers starting from the end of the string and reading backwards?

Starting at the front of the string I can do this:

someword: 12345
s/someword: [0-9][0-9]/someword: ==/g;
someword: ==345

But that will only work if the string is five numbers long. Regardless of the length of the number string, I want to keep the last three numbers.

Thank you

2
  • Have you tried anything?
    – Samsquanch
    Aug 11, 2014 at 22:44
  • I should have been a little less generic. The someword:<space> <number string> comes up hundreds of times in the file and the <number string> is always different. That's why I'm using the global substitution the way I have it above. Aug 12, 2014 at 23:53

2 Answers 2

2

I would use an executable substitution.

This code finds multiple digits that are followed by three more digits, and replaces them with the same number of equals = signs

my $s = 'someword: 12345678';

$s =~ s/ (\d+) (?=\d{3}) / '=' x length $1 /xe;

print $s;

output

someword: =====678
1
  • Clever regex. Wonder if there is any downside for not anchoring $ to match the last 3. Aug 12, 2014 at 0:55
0

Just use a positive lookahead assertion:

my $string = 'someword: 12345';

$string =~ s/\d(?=\d{3})/=/g;

print "$string\n";

Outputs:

someword: ==345
1
  • I don't like the thought of that replacing one digit at a time, but I'm sure it's not a problem
    – Borodin
    Aug 11, 2014 at 23:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.