Regular expression to replace second occurrence of dot

Viewed 1220

String is Hello.world.hello. I wanted to replace the second occurrence of the dot with '_'.

str = "Hello. world. Hello!" 
x = re.sub(r'^((.){1}).', r'\1_', str)
#x = str.find(str.find('.')
print(x)

The output I am getting is 'H_llo. world. Hello!'. What should be the correct solution

2 Answers

You can use

import re
text = "Hello. world. Hello!" 
print( re.sub(r'^([^.]*\.[^.]*)\.', r'\1_', text) )
# => Hello. world_ Hello!

See the Python demo and the regex demo.

Details:

  • ^ - start of string
  • ([^.]*\.[^.]*) - Group 1: any zero or more chars other than a ., a dot and again any 0+ non-dots
  • \. - a dot.

The replacement is Group 1 value + _.

It is also possible to do without a regex:

text = "Hello. world. Hello!" 
chunks = text.split('.', 2) # split the text twice
if len(chunks) > 2:         # if there are more than 2 items
    print( fr'{".".join(chunks[0:2])}_{chunks[2]}' )
else:
    print(text)             # Replace the second dot or print the original
# => Hello. world_ Hello!

See the Python demo.

With your shown samples, could you please try following. Written and tested in Python3.8

import re
str1 = "Hello. world. Hello!"
re.sub(r'^(.*?\.)([^.]*)\.(.*)$', r'\1\2_\3', str1)
'Hello. world_ Hello!'

Explanation: Simply importing re function of Python3.8 then creating str1 variable with value. Then using re.sub function to replace 2nd dot with _ as per requirement. In re.sub function on first argument giving regex to match everything apart from 2nd dot(in 3 capturing groups) and replacing them as per need with respective capturing groups placing _ on place of 2nd dot.

Explanation of regex:

^(.*?\.)  ##Creating 1st capturing group, where Matching till 1st dot from staring of value.
([^.]*)   ##Creating 2nd capturing group, matching just before dot(2nd dot) here.
\.        ##Matching exact literal dot here.
(.*)$     ##Matching/keeping everything else till last of value in 3rd capturing group.
Related