Place an integer using regex

I am using regular expressions with python map to input a specific number in the version number:

10.2.11

I want to convert the second element to be null padded, so it looks like this:

02/10/11

My regex looks like this:

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

      

If I am simply discarding the relevant groups, I use this line:

\1\2\3

      

When I use my favorite regex test ( http://kodos.sourceforge.net/ ) I can't load it into the second group. I've tried \ 1 \ 20 \ 3, but this interprets the second link as 20, not 2.

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

I guess I just need to escape the relevant groups line, but I can't figure it out. Thanks in advance for any help.

+1


a source to share


4 answers


How about removing .

from regex?

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

      



replaced by:

\1.0\2.\3

      

+1


a source


How about a completely different approach?



nums = version_string.split('.')
print ".".join("%02d" % int(n) for n in nums)

      

+3


a source


Try the following:

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

      

And replace the match with 0\1

. This will make any number at least two digits long.

+1


a source


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

0


a source







All Articles