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

正则表达式需求:忽略引号内转义字符,匹配单引号内内容

Matching Content Inside Single Quotes with Escaped Quotes

Hey there! I totally feel your pain—even with years of regex experience under your belt, escaped characters can throw a real wrench in things. Let’s work through this together.

The Problem with Basic Regex

If you tried a simple pattern like '([^']*)', it’ll fail the second it hits an escaped single quote (\'). That’s because [^'] is designed to match any character except a single quote, so it stops dead at the first ' it sees—even if that quote is escaped and shouldn’t end the match.

The Solution: A Regex That Handles Escapes

Here’s a reliable pattern that accounts for escaped single quotes properly:

'((?:\\.|[^'\\])*)'

Let’s break down what each part does to make it clear:

  • ' : Matches the opening single quote to start our target range.
  • (?:\\.|[^'\\])* : A non-capturing group that matches any number of valid characters inside the quotes:
    • \\. : Catches escaped characters (like \'—the \\ grabs the backslash, and . matches the character it’s escaping, including another single quote).
    • [^'\\] : Matches any regular, unescaped character that’s not a single quote or backslash.
  • ' : Matches the closing single quote to end our target range.
  • The outer (...) is a capturing group that grabs exactly the content inside the quotes (without the quotes themselves, if that’s what you need).

Example Usage

Say your input string is:

He said 'I\'m heading to the market' and walked away.

This regex will capture I\'m heading to the market as the matched content—no premature truncation!

Quick Notes for Specific Languages

  • In Python, use a raw string to avoid double-escaping headaches:
    import re
    text = "He said 'I\\'m heading to the market' and walked away."
    match = re.search(r"'((?:\\.|[^'\\])*)'", text)
    print(match.group(1))  # Output: I\'m heading to the market
    
  • In JavaScript, write the regex directly (just remember to escape backslashes in your string):
    const text = "He said 'I\\'m heading to the market' and walked away.";
    const regex = /'((?:\\.|[^'\\])*)'/;
    const match = text.match(regex);
    console.log(match[1]); // Output: I\'m heading to the market
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:40:09