Problems worthy of attack prove their worth by hitting back. —Piet Hein

Tuesday, 2 October 2007

Zero-width Negative Lookbehind

Mainly for my own reference:

perl -ple 's/(?<![+-\d])(\d+)/\+$1/g'

This will ensure all integers in a string have a leading sign. So for example, "+163, 163, -163" becomes "+163, +163, -163". It works using a zero-width negative lookbehind assertion: in this case the only "163" in the string that matches is the one that is not preceded by a plus sign, a minus sign, or a digit.

This came up at work today (thanks Robin).

1 comment:

Ray Toal said...

Better to say [-+\d] instead of [+-\d] because in some regex languages (such as Java's) the dash in the second form is interpreted as a range.