user2258552
user2258552

Reputation: 822

Perl regexp partial replacement

I want to replace all instances of a number in a string, but only if that number is the in the nth column where the columns are space-delimited.

This is what I had so far:

$_ =~ s/\s+([^\s]+\s+){$numcols}$i(.*)\n/$rep/;

Basically, there will be a few spaces, and then there will be: (non-spaces (column) followed by spaces) for $numcols times. Then, there will be $i, where $i is the number I want to replace, followed by some characters I don't care about and a newline. However, I don't want to replace ALL OF THAT with $rep, but only $i. How do I do that?

Upvotes: 0

Views: 253

Answers (1)

Paul Roub
Paul Roub

Reputation: 36438

Something like this:

$_ =~ s/^(\s+(?:[^\s]+\s+){$numcols})$i/$1$rep/;

We're catching everything before $i as one group (with a non-capturing group denoted by ?: in the middle of it). We're keeping all that, replacing just $i, and leaving the rest of the string alone.

Upvotes: 2

Related Questions