You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python正则:仅转义双引号内字符的实现方法求助

Solution for Escaping Only Inside Double-Quoted Sections in Python 2.7

Got it, let's work through this problem. The core challenge is targeting only the backslashes and double quotes that sit inside double-quoted segments of your string—leaving everything outside those quotes untouched. Here's a solid implementation using regular expressions and a callback function in Python 2.7:

Code Implementation

import re

def escape_quoted_content(match):
    # Extract the content wrapped inside the double quotes
    inner_content = match.group(1)
    # First escape backslashes (critical to do this first!)
    escaped_backslashes = inner_content.replace('\\', '\\\\')
    # Then escape any double quotes inside the section
    escaped_quotes = escaped_backslashes.replace('"', '\\"')
    # Re-wrap the processed content in double quotes
    return '"{}"'.format(escaped_quotes)

# Your original string (Python 2.7 representation)
original = 'NotEscaped"S\\tr"ing"'
# Process the string with regex substitution
processed = re.sub(r'"([^"\\]*(?:\\.[^"\\]*)*)"', escape_quoted_content, original)

# Check the result using repr() to see the escaped format
print(repr(processed))
# Output: 'NotEscaped"S\\\\tr\\"ing"'

Breakdown of the Regex

The pattern r'"([^"\\]*(?:\\.[^"\\]*)*)"' is designed to reliably match double-quoted sections even if they already contain escaped characters:

  • ": Matches the opening double quote.
  • ([^"\\]*(?:\\.[^"\\]*)*): The capturing group that grabs the content inside the quotes:
    • [^"\\]*: Matches any character that isn't a double quote or backslash (zero or more times).
    • (?:\\.[^"\\]*)*: A non-capturing group that handles escaped characters: it matches a backslash followed by any character, then more non-quote/non-backslash characters—repeating as needed. This ensures we don't break existing escaped content.
  • ": Matches the closing double quote.

Why the Callback Order Matters

We first escape backslashes, then double quotes. If we reversed this order, the backslash we added to escape a quote would itself get escaped, leading to incorrect results (like \\" becoming \\\\\" instead of just \\").

Verification

For your example input 'NotEscaped"S\\tr"ing"', the code produces the exact output you wanted: 'NotEscaped"S\\\\tr\\"ing"'—the backslash in S\\tr becomes S\\\\tr, and the trailing quote inside the section becomes \\".

内容的提问来源于stack exchange,提问作者Gad82

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:39:37