Reputation: 2131
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)
Upvotes: 0
Views: 2820
Reputation: 154
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|'))
Upvotes: 0
Reputation: 943
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
Upvotes: 0
Reputation: 195553
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)
Upvotes: 7