0

I need to replace dots within brackets with re with another string:

from

a = 'hello.mate(how.are.you)'

to

b = 'hello.mate(how|DOT|are|DOT|you)

I tried to use /( to highlight the beginning of the brackets and /) for the closing, but I am unclear how to capture the simple dot in between.

The two most pertinent examples

These two questions clearly faced the exact same problem, expecially question #2, but I can't seem to capture just a single dot in the re.sub

Regex replace text between delimiters in python

Regex using Python to replace dot of floating numbers with "dot"

Attempted solutions

Various ineffective attempts based on the examples above include:

b = re.sub(r'\(.\)','|DOT|', a)
b = re.sub(r'\(\.\)','|DOT|', a)
b = re.sub(r'\([.]\)','|DOT|', a)
b = re.sub(r'\([\.]\)','|DOT|', a)
Pythonic
  • 2,091
  • 3
  • 21
  • 34

3 Answers3

7

You can nest re.sub to first match string inside brackets and then substitute . for |DOT|:

import re

a = 'hello.mate(how.are.you)'

s = re.sub(r'\((.*?)\)', lambda g: re.sub(r'\.', '|DOT|', g[0]), a)
print(s)

Prints:

hello.mate(how|DOT|are|DOT|you)
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0

I tryed something like :

import re




a = 'hello.mate(.are.you)'




res = r'\([^\.\)]*(?:(?P<dot>\.)[^\.\)]*)+\)'

p = re.compile(res)

for m in  re.finditer(p,  a):

    print(m.start('dot'), m.end('dot'))

but i do not understand why dot is only ones captured

user8426627
  • 903
  • 1
  • 9
  • 19
0

Try this,

import re
a = 'hello.mate(how.are.you)'  
content_in_brackets = re.findall(r'\((.*?)\)', a)
for con in content_in_brackets:
    a = a.replace(con, con.replace('.', '|DOT|'))