如何用JavaScript正则匹配Markdown代码块外的单引号
Ah, I get it—you're trying to swap straight single quotes (') for smart ones (’) but only when they're not inside Markdown code blocks (either inline with single backticks or fenced with triple backticks). Your current regex is catching quotes inside code blocks because it isn't properly excluding those sections first.
Here's a working solution using JavaScript regex (which VSCode uses):
Regex Pattern
(```[\s\S]*?```|`[^`]+`)|'
Replacement String
$1’
How It Works
Let's break down the regex step by step:
- Code block matching group:
(```[\s\S]*?```|[^`]+`)`[\s\S]*?: Catches fenced code blocks (triple backticks). The[\s\S]*?ensures we match everything inside the block (including newlines) without greedily extending past the closing triple backticks.|[^]+``: Catches inline code blocks (single backticks).[^]+matches any character except a backtick, so it only targets content within a single pair of backticks.
- Single quote match:
'— this only matches straight quotes that aren't part of a code block (since the code block group takes precedence in the alternation).
In the replacement:
- If the first group (
$1) exists (meaning we matched a code block), we just put that block back exactly as it was. - If there's no
$1, we replace the matched straight quote with the smart quote’.
Testing with Your Example
Using your sample text:
match this one ' ``` don't match this ``` match this as well ' ``` not this one ' ``` yes to this one ' `not this ' one`
After replacement, it becomes:
match this one ’ ``` don't match this ``` match this as well ’ ``` not this one ’ ``` yes to this one ’ `not this ' one`
Perfect—all quotes outside code blocks are swapped, while the ones inside (both fenced and inline) stay untouched. Just plug this regex and replacement into your VSCode RegReplace settings, and you're good to go!
内容的提问来源于stack exchange,提问作者Geob-o-matic

