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

JavaScript正则表达式:分割逗号与换行但排除转义逗号

Solution for Splitting Commas/Newlines Without Splitting Escaped Commas

Hey there! Let's tweak your existing split regex to handle escaped commas properly. Your current regex /[\r\n,]+/g splits on any comma or newline, but it doesn't account for commas that are escaped with a backslash (\,). Here's how to fix it:

The Updated Regex

Use this regex instead:

/(?<!\\)[\r\n,]+/g

How It Works

Let's break down the parts to make it clear:

  • (?<!\\): This is a negative lookbehind assertion. It checks that the character immediately before the comma/newline is not a backslash. That way, any comma wrapped in an escape (\,) gets skipped by the split logic.
  • [\r\n,]+: This part matches one or more commas, carriage returns, or newlines—just like your original regex, but now only when they aren't preceded by an escape character.

Example Usage

Let's test it with your sample inputs to confirm it works:

// Basic case with no escaped commas
const str1 = "foo,bar,baz";
console.log(str1.split(/(?<!\\)[\r\n,]+/g)); 
// Output: ["foo", "bar", "baz"]

// Case with an escaped comma
const str2 = "foo,bar\\,baz,42";
console.log(str2.split(/(?<!\\)[\r\n,]+/g)); 
// Output: ["foo", "bar\\,baz", "42"]

Edge Case Note

If you run into a scenario with double backslashes (escaping the backslash itself, like foo\\\\,bar), this regex still behaves correctly. For example:

const str3 = "foo\\\\,bar,baz";
console.log(str3.split(/(?<!\\)[\r\n,]+/g)); 
// Output: ["foo\\\\", "bar", "baz"]

This works because the negative lookbehind only flags commas preceded by a single unescaped backslash.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:59:35