tags:

views:

709

answers:

4

I'm using regular expressions with a python framework to pad a specific number in a version number:

10.2.11

I want to transform the second element to be padded with a zero, so it looks like this:

10.02.11

My regular expression looks like this:

^(\d{2}\.)(\d{1})([\.].*)

If I just regurgitate back the matching groups, I use this string:

\1\2\3

When I use my favorite regular expression test harness (http://kodos.sourceforge.net/), I can't get it to pad the second group. I tried \1\20\3, but that interprets the second reference as 20, and not 2.

Because of the library I'm using this with, I need it to be a one liner. The library takes a regular expression string, and then a string for what should be used to replace it with.

I'm assuming I just need to escape the matching groups string, but I can't figure it out. Thanks in advance for any help.

A: 

Does your library support named groups? That might solve your problem.

Dave Webb
no, it doesn't support named groups.
Dan Wolchonok
A: 

Try this:

(^\d(?=\.)|(?<=\.)\d(?=\.)|(?<=\.)\d$)

And replace the match by 0\1. This will make any number at least two digits long.

Gumbo
this didn't match my string: 10.2.11
Dan Wolchonok
It works for me: `re.compile(r"(^\d(?=\.)|(?<=\.)\d(?=\.)|(?<=\.)\d$)").sub(r"0\1", "10.2.11")`.
Gumbo
+1  A: 

What about removing the . from the regex?

^(\d{2})\.(\d{1})[\.](.*)

replace with:

\1.0\2.\3
Alex B
I love the "outside of the box" thinking. Thanks!
Dan Wolchonok
+1  A: 

How about a completely different approach?

nums = version_string.split('.')
print ".".join("%02d" % int(n) for n in nums)
EOL
I feel compelled to upvote simple Python solutions that are regex-free. (It would probably be a different story if it were Perl.)
John Y