Problems worthy of attack prove their worth by hitting back. —Piet Hein
Showing posts with label Regular Expressions. Show all posts
Showing posts with label Regular Expressions. Show all posts

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).