1

I want to delete copies of 'i' in this example, tried using groups but it's not working. Where am I doing this wrong?

import re

a = '123iiii'
b = re.match('.*i(i+)', a)
print(b.group(1))
>>> i
a = re.sub(b.group(1), '', a)
print(a)
>>> 123

Desired result is '123i'.
Thanks for the answer.

1
  • 1
    you want just to leave one of it? Commented Nov 16, 2019 at 17:34

4 Answers 4

2

Maybe,

([^i]*i)i*([^\r\n]*)

and a replacement of,

\1\2

might be OK to look into.

Test

import re

string = '''
123iiii
123iiiiabc
123i
'''

expression = r'([^i]*i)i*([^\r\n]*)'

print(re.sub(expression, r'\1\2', string))

Output

123i
123iabc
123i

If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

2

It seems that what you need is:

import re

a = '123iiii'
a = re.sub(r"i+", "i", a)

print(a)
>>> 123i

Comments

1

You can achieve your goal by simply using the sub function to replace a sequence of i's with a single i

import re

a = '123iiii'
a = re.sub(r'i+', 'i', a)
print(a)

Comments

0

The following will work even if you have the i's in multiple places in the string.

import re

s = '123iiii657iii'
re.sub('i+','i',s)

Output:

'123i675i'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.