I'm struggling to understand a seemingly simple problem. What I want to do is to change a string slightly, by wrapping all the values inside a separator such as parentheses ()
with a character like quotes, and then title casing all the words. But I'm unable to get it to fully working as expected.
For example, given a simple string:
hello(world)
I want to replace the part inside the paranthesis by modifying it slightly - in this case by wrapping it with quotes:
hello("World")
I'm able to get this far, but the problem is it's not working when I have nested parantheses:
hi (hello(world(a test)))
I would like to end up with:
hi ("Hello("World("A Test")")")
But I'm not getting a result as expected ufortunately.
Here's my code that I was testing with. By the way, I got the idea to get the indices of a character in a string from this article here.
import re
def wrap_values_within_group(s: str, delimiter_group='()'):
start_char, end_char = delimiter_group
start_indices = [i.start() for i in re.finditer(re.escape(start_char), s)]
end_indices = [i.start() for i in re.finditer(re.escape(end_char), s)]
parts = []
for i in range(len(start_indices)):
start_pos = start_indices[i]
end_pos = end_indices[-i]
repl_pos = start_pos + 1
parts.append(s[:repl_pos])
parts.append('"' + s[repl_pos:end_pos].title() + '"')
parts.append(s[end_pos:])
return ''.join(parts)
I understand I can likely achieve this without regex, but I'd like to see if it's possible without using regex substitutions if possible. I'd also prefer to do this within one function ideally, as I'm thinking that calling a function repeatedly to make the replacements might be a bit slow. Any suggestions are welcome.