# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = (r"(?x) # Free-Spacing\n"
r"(?(DEFINE) # Define a few subroutines\n"
r" (?<double>“(?:(?!&[lr]squo;).)*”) # full set of doubles (no quotes inside)\n"
r" (?<single>‘(?:(?!&[lr]dquo;).)*’) # full set of singles (no quotes inside)\n"
r" (?<notquotes>(?:(?!&[lr][sd]quo;).)*) # chars that are not quotes\n"
r") # end DEFINE\n\n"
r"^ # Start of string\n"
r"( # Start group: balanced portion\n"
r"(?: # Start non-capture group\n"
r" (?¬quotes) # Any non-quote chars\n"
r" &l(?<type>[sd])quo; # Opening quote, capture single or double type\n"
r" # any full singles, doubles, not quotes or recursion\n"
r" (?:(?&single)|(?&double)|(?¬quotes)|(?R))*\n"
r" &r\k<type>quo; # Closing quote of the correct type\n"
r")*+ # Repeat non-capture group\n"
r") # end balanced portion\n"
r"\K\n"
r"(\n"
r"(?¬quotes)\n"
r"&r([sd])quo; # unmatched quote\n"
r")")
test_str = ("“Full Quote” The Left Quote is Missing”\n")
subst = "&l\\7quo;\\6"
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 1)
if result:
print (result)
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Python, please visit: https://docs.python.org/3/library/re.html