I have written a regex to identify the words only starting, only ending with a single quote (')
or both starting/ending:
re_quotes_front = r"(?:\s+|^)(?P<g1>'\w+)(?=\s+|$)"
re_quotes_end = r"(?:\s+|^)(?P<g2>\w+')(?=\s+|$)"
re_quotes_front_end = r"(?:\s+|^)(?P<g3>'\w+')(?=\s+|$)"
generic_quotes = r"%s|%s|%s" % (re_quotes_front, re_quotes_end, re_quotes_front_end)
Now I want to replace the matching group with a space between '
and the matched word
.
For example, let's say we have to match the regex with the below string:
snippet = "shot perhaps 'artistically' with 'handheld cameras 'devices'"
I want to replace all of them using one regex, i.e., generic_quotes
. Can that be done?
The output should be:
"shot perhaps ' artistically ' with ' handheld cameras ' devices '"
Even for any one of the regex, the below does not work:
result = re.sub(re_quotes_front, r"\g<g1>".replace("'", " ' "), snippet)
I should get the word 'handheld
converted to ' handheld
(note the space before and after the quote) and that's not happening. I couldn't understand how this is working. Rather, I am getting the output:
"shot perhaps 'artistically' with'handheld cameras'em 'asdsd'"
How can I reference the word using the <group_name1>
and modify it?