0

I have some string like this

'    12    2    89   29   11    92     92     10'

(all the numbers are positive integers so no - and no .), and I want to extract all numbers from it, edit some of the numbers, and then put them all together with the same whitespaces. For example, if I change the number 11 to 22, I want the final string as

'    12    2    89   29   22    92     92     10'

I did some search and most questions disregard the whitespaces and only care about the numbers. I tried

match = re.match((\s*(\d+)){8}, str)

but match.group(0) gives me the whole string,, match.group(1) gives me the first match \ 12 (I added the \ otherwise the website won't show the leading whitespaces), and match.group(2) gives me 12. But it won't give me any numbers after that, any index higher than 2 gives me an error. I don't think my approach is the correct one, what is the right way to do this?

I just tried re.split('(\d+)', str) and that seems to be what I need.

LWZ
  • 11,670
  • 22
  • 61
  • 79
  • How about just `\s+\d+`. [Regex Demo](https://regex101.com/r/sckKLO/1) – pault Jan 30 '18 at 01:27
  • What if you change 99 to 101? Should you lose a whitespace, or get a longer line? –  Jan 30 '18 at 01:39
  • already exists one answer at this link: [Python RegEx multiple groups ](https://stackoverflow.com/questions/4963691/python-regex-multiple-groups) – Sphinx Jan 30 '18 at 01:59
  • @Evert Just keep the same number of of whitespace is fine. – LWZ Jan 30 '18 at 19:06

2 Answers2

1

I'd recommend using a regular expression with non-capturing groups, to get a list of 'space' parts and 'number' parts:

In [15]: text = '    12    2    89   29   11    92     92     10'
In [16]: parts = re.findall('((?: +)|(?:[0-9]+))', text)
In [17]: parts
Out[17]: ['    ', '12', '    ', '2', '    ', '89', '   ', '29', '   ',
  '11', '    ', '92', '     ', '92', '     ', '10']

Then you can do:

for index, part in enumerate(parts):
    if part == '11':
        parts[index] = '22'
replaced = ''.join(parts)

(or whatever match and replacement you want to do).

Nathan Vērzemnieks
  • 5,495
  • 1
  • 11
  • 23
0

Match all numbers with spaces, change desired number and join array.

import re

newNum = '125'
text = '    12    2    89   29   11    92     92     10'
                                              ^^
marray = re.findall(r'\s+\d+', text)
marray[6] = re.sub(r'\d+', newNum, marray[6])

print(marray) 

['    12', '    2', '    89', '   29', '   11', '    92', '     125', '     10']
Srdjan M.
  • 3,310
  • 3
  • 13
  • 34