Delete extra characters apart from starting and ending in a string in python
Question: I have data of the form:

    
    
    "C def geh.#- ijk "<> ""^^xsd:date.
    

Now for the last part of the above string i.e. "C def geh.#- ijk "<>
""^^xsd:date -- i.e the part which begins and ends with quotes. I want to keep
just the beginning and ending quotes and delete all the other quotes and <>,
etc. except #,-,.,_,(,) which come in between. Can someone please suggest how
can i do it. My expected output should appear as:

    
    
    "C def geh.#- ijk "^^xsd:date.
    


Answer: Assuming that there always will be a match:

    
    
    import re
    
    def cleanup(str): 
        return ''.join(re.match('(\"[^\"]+\").*?(\^\^xsd\:date\.)', str).groups())
    
    >>> s = """"C def geh.#- ijk "<> ""^^xsd:date."""
    >>> cleanup(s)
    '"C def geh.#- ijk "^^xsd:date.'
    

UPDATE If the dot at the end of the string might or might not appear, use this
(and I forgot the dollar sign to mark the end):

    
    
    def cleanup(str): 
        return ''.join(re.match('(\"[^\"]+\").*?(\^\^xsd\:date\.?)$', str).groups())
    
    >>> s = '"1980-"05"-26"^^xsd:date'
    >>> cleanup(s)
    '"1980-"^^xsd:date'
    

If you want to handle the situation when there is no match (e.g. return empty
string), then it could be done like this:

    
    
    def cleanup(str):
        try:
            return ''.join(re.match('(\"[^\"]+\").*?(\^\^xsd\:date\.?)$', str).groups())
        except AttributeError:
            return ''
    
    >>> cleanup("asdfadf")
    ''
    

UPDATE after getting more explanations from OP (need to cleanup the contents
between the first and last quotes and return the rest unchanged):

    
    
    def cleanup(str):
        left_index = s.find('\"')
        right_index = s.rfind('\"')
        if left_index==right_index: 
            return str
        else:
            cleaned = re.sub('[^0-9a-zA-Z\#\-\.\_\(\)]','',s[left_index+1:right_index])
            return str[:left_index+1]+cleaned+str[right_index:]
    
    >>> cleanup(s)
    '"1980-05-26"^^xsd:date'
    

