Question

I have a problem that probably is very easy to solve. I have a script that takes numbers from various places does math with them and then prints the results as strings.

This is a sample

type("c", KEY_CTRL)
LeInput = Env.getClipboard().strip() #Takes stuff from clipboard
LeInput = LeInput.replace("-","") #Quick replace
Variable = int(LeInput) + 5 #Simple math operation

StringOut = str(Variable) #Converts it to string
popup(StringOut) #shows result for the amazed user

But what I want to do is to add the "-" signs again as per XXXX-XX-XX but I have no idea on how to do this with Regex etc. The only solution I have is dividing it by 10^N to split it into smaller and smaller integers. As an example:

int 543442/100 = 5434 giving the first string the number 5434, and then repeat process until i have split it enough times to get my 5434-42 or whatever.

So how do I insert any symbol at the N:th character?

OK, so here is the Jython solution based on the answer from Tenub

import re
strOut = re.sub(r'^(\d{4})(.{2})(.{2})', r'\1-\2-\3', strIn)

This can be worth noting when doing Regex with Jython:

The solution is to use Python’s raw string notation for regular expression patterns; backslashes are not handled in any special way in a string literal prefixed with 'r'. So r"\n" is a two- character *string containing '\' and 'n', while "\n" is a one-character string* containing a newline. Usually patterns will be expressed in Python *code using this raw string notation.*

Here is a working example http://regex101.com/r/oN2wF1

Was it helpful?

Solution

In that case you could do a replace with the following:

(\d{4})(\d{2})(\d+)

to

$1-$2-$3
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top