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:
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.
Post a Comment