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

如何用正则表达式移除单词两侧成对双引号而非单个双引号?

Got it, let's break down how to solve this exactly as you need it. Your goal is to remove paired double quotes only when they wrap a standalone "word" (no spaces inside), keep single unpaired quotes like 3.5", and leave outer quotes intact when they contain spaces or other quotes (like the outer "cool "bounce" in your example).

Solution

Basic Case (No Escaped Quotes)

Use this regex to target quotes wrapping continuous non-whitespace characters (your "words"):

"(\S+)"
  • " : Matches the opening double quote
  • (\S+) : Capture group that grabs one or more non-whitespace characters (the word we want to keep)
  • " : Matches the closing double quote

Replace the entire match with the captured group ($1 in most regex engines, or \1 in some like sed).

Example in JavaScript:

const originalText = '3.5" hdd "hello" "cool "bounce" single sentence with out quotes';
const fixedText = originalText.replace(/"(\S+)"/g, '$1');
console.log(fixedText);
// Output: 3.5" hdd hello "cool bounce single sentence with out quotes

This will strip quotes from "hello" and "bounce" exactly as you wanted, leaving the 3.5" quote and the outer "cool ..." quotes untouched.

For Scenarios with Escaped Quotes

If you need to handle cases where words contain escaped quotes (like "he\"llo"), use this more robust regex that ignores escaped quotes inside the wrapped content:

"([^"\\]*(?:\\.[^"\\]*)*)"

This regex ensures we only match paired quotes where all internal quotes are escaped (so it won't mistakenly match outer quotes that contain unescaped quotes like "cool "bounce").

Example:

const textWithEscapes = '3.5" hdd "he\\"llo" "cool "bounce"';
const result = textWithEscapes.replace(/"([^"\\]*(?:\\.[^"\\]*)*)"/g, '$1');
console.log(result);
// Output: 3.5" hdd he\"llo "cool bounce

Why Your Original Regex Didn't Work

Your regex "([^\\"]|\\")*" is too broad—it will match any paired quotes, even those wrapping content with unescaped quotes (like "cool " in your example). This leads to accidentally stripping outer quotes you wanted to keep. The regexes above narrow down the target to exactly the quote-wrapped words you need to modify.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 10:11:20