简体   繁体   中英

Replacing consecutive symbol with number digit in python using regex

Here's the case :

str='myfile.#.#####-########.ext'

i want to replace the # with number : 456 so it should be :

str = 'myfile.456.00456-00000456.ext'

the second case :

str= 'myfile.%012d.tga'

replace the pattern with number 456 so it will become :

str= 'myfile.000000000456.tga'

i can solve this using string replacement method by grab the pattern then count the digits then fill with zero pad. Right now , i want to know how to do it using regex in python ? Can anyone help ? Thanks a lot.

The second case is straight forward and does not require regex and a regex would be an overkill. I would suggest you to use a string format replacement

'myfile.%012d.tga' % 456
Out[21]: 'myfile.000000000456.tga'

The first case is tricky but possible

>>> def repl(m):
    return "{{0:0{}}}".format(len(m.group(1)))

>>> re.sub(r"(#+)", repl, st).format(456)
'myfile.456.00456-00000456.ext'

Through re.sub without format function.

>>> s = 'myfile.#.#####-########.ext'
>>> re.sub(r'#+', lambda m: '456' if len(m.group()) == 1 else m.group()[:-1].replace('#', '0') + '456', s)
'myfile.456.0000456-0000000456.ext'

For the second case,

>>> s = 'myfile.%012d.tga'
>>> re.sub(r'%(\d+)d', lambda m: str('0' * int(m.group(1)))[:-1] + '456', s)
'myfile.00000000000456.tga'

Finally, thanks for all who has answered my question. That 'lambda' thing reallt give me the idea , here's the answer for my question :

my first case using '#' :

s = 'myfile.##.####.########.ext'
print re.sub('#+', lambda x : '456'.zfill(len(x.group())) ,s)

---> myfile.456.0456.00000456.ext

my second case using %0xd format :

s = 'myfile.%06d--%012d--%02d.ext'
print re.sub('%0[0-9]+d', lambda x : x.group() % 456 ,s)

r---> myfile.000456--000000000456--456.ext

Here's just simple combination of both case above :

s = 'myfile.##.####.########.%06d---%02d.ext'
x=re.sub('#+', lambda x : '456'.zfill(len(x.group())) ,s)
print re.sub('%0[0-9]+d', lambda x : x.group() % 456 ,x)

---> myfile.456.0456.00000456.000456---456.ext

Don't forget to 'import re' to use the regex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM