Regular expression replace except first and last characters

前端 未结 3 427
一个人的身影
一个人的身影 2021-01-20 08:42

What is a regular expression to replace doublequotes (\") in a string with escape backslash followed by doublequotes (\\\") except at the first and last characters of the s

相关标签:
3条回答
  • 2021-01-20 08:54

    Unfortunately, I don't think you can do that with a single regex. You can fake it, though, with three regexes.

    >>> x = '"This is "what" it is"'
    >>> print x
    "This is "what" it is"
    >>> x = re.sub(r'"',r'\\"',x)
    >>> print x
    \"This is \"what\" it is\"
    >>> x = re.sub(r'^\\"','"',x)
    >>> print x
    "This is \"what\" it is\"
    >>> x = re.sub(r'\\"$','"',x)
    >>> print x
    "This is \"what\" it is"
    

    The first regex changes all quotes into escaped quotes.

    The second regex changes the leading quote back (no effect if no leading quote present).

    The third regex changes the trailing quote back (no effect if no trailing quote present).

    0 讨论(0)
  • 2021-01-20 09:06

    I don't know about you, but I'd do it the easy way:

    '"{}"'.format(s[1:-1].replace('"',r'\"'))
    

    Of course, this makes a whole bunch of assumptions -- The strongest being that the first and last characters are always double quotes ...

    Maybe this is a little better:

    '{0}{1}{2}'.format(s[0],s[1:-1].replace('"',r'\"'),s[-1])
    

    which preserves the first and last characters and escapes all double quotes in the middle.

    0 讨论(0)
  • 2021-01-20 09:11

    As pointed out by @mgilson, you can just slice the first and last characters off so this regex is basically pointless

    >>> print re.sub(r'(?<!^)"(?!$)', '\\"', '"This is a "Test""')
    "This is a \"Test\""
    >>> print re.sub(r'(?<!^)"(?!$)', '\\"', '"This is a Test"')
    "This is a Test"
    
    0 讨论(0)
提交回复
热议问题