tags:

views:

44

answers:

3

Hi,

I'm trying to fix a file full of 1- and 2-digit numbers to make them all 2 digits long.

The file is of the form:

10,5,2
2,4,5
7,7,12
...

I've managed to match the problem numbers with:

(^|,)(\d)(,|$)

All I want to do now is replace the offending string with:

${1}0$2$3

but TextMate gives me:

10${1}05,2

Any ideas?

Thanks in advance, Ross

A: 

You need not ${1} - replace strings support only up to nine groups maximum - so it won't mistake it for $10.

Replace with $10$2$3

Amarghosh
+1, likewise :)
Tim Pietzcker
When I try this, I find that $10 is replaced with nothing, so: 25,9,becomes: 259,
rossmcf
@rossmcf This is the normal behavior of replacing with regexes. I don't have textmate, but if you're right, that might be a bug in it.
Amarghosh
@Tim can you confirm if it's a bug or not - the linked page doesn't say anything in particular about the behavior of `$n` if n > 9 - but supporting `$10` doesn't sound like a good idea.
Amarghosh
+2  A: 

Note: Tim's solution is simpler and solves this problem, but I'll leave this here for reference, in case someone has a similar but more complex problem, which using lookarounds can support.


A simpler way than your expression is to replace:

(?<!\d)\d(?!\d)

With:

0$0

Which is "replace all single digits with 0 then itself".

The regex is:
Negative lookbehind to not find a digit (?<!\d)
A single digit: \d
Negative lookahead to not find a digit (?!\d)

Single this is a positional match (not a character match), it caters for both comma and start/end positions.

The $0 part says "entire match" - since the lookbehind/ahead match positions, this will contain the single digit that was matched.

Peter Boughton
Thanks. Must play with lookbehind/aheads. I'm a regex n00b.
rossmcf
+5  A: 

According to this, TextMate supports word boundary anchors, so you could also search for \b\d\b and replace all with 0$0. (Thanks to Peter Boughton for the suggestion!)

This has the advantage of catching all the numbers in one go - your solution will have to be applied at least twice because the regex engine has already consumed the comma before the next number after a successful replace.

Tim Pietzcker
+1 for the value added answer!
Amarghosh
According to that link, $0 is supported, so you can simplify the regex to `\b\d\b` and use 0$0 in the result.
Peter Boughton
Even better :) Serves me right not reading it more thoroughly. Edited my answer.
Tim Pietzcker
Thanks Tim,A very tidy solution.
rossmcf