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

如何在C#中实现移除无空格方括号并转换含空格方括号为双引号?

问题与解决方案

问题说明

我参考了Stack Overflow上的《Remove square brackets if content within the square bracket does not contain spaces》方案,在Notepad++里运行正常,但移植到C#后出现大量错误替换。我的需求是处理SQL语句:

  • 移除内容不含空格的方括号(比如[dbo]变成dbo)
  • 将内容含空格的方括号替换为双引号(比如[Date Started]变成"Date Started")

原SQL语句:

CREATE TABLE [dbo].[Event](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Date Started] [datetime] NOT NULL,
    [StartTime] [time](7) NOT NULL,
    [Description] [nvarchar](250) NULL,
    [AudioLocation] [nvarchar](max) NOT NULL,
    [PlayerLocation] [nvarchar](max) NOT NULL,
 CONSTRAINT [PK_dbo.Event] PRIMARY KEY CLUSTERED

期望得到的目标格式:

CREATE TABLE dbo.Event(
    ID int IDENTITY(1,1) NOT NULL,
    "Date Started" datetime NOT NULL,
    StartTime time(7) NOT NULL,
    Description nvarchar(250) NULL,
    AudioLocation nvarchar(max) NOT NULL,
    PlayerLocation nvarchar(max) NOT NULL,
 CONSTRAINT PK_dbo.Event PRIMARY KEY CLUSTERED

原C#代码(存在错误):

str.Regex.Replace(str, @"\[(\w+)\]|\[([^\]]+)\]"), "(?1$1:(?2\"$2\"))")

原代码问题分析

  1. 语法错误:写法颠倒,正确调用应为Regex.Replace(str, 正则表达式, 替换内容),且括号配对错误;
  2. 正则语法不兼容:C#的.NET正则引擎不支持Notepad++所用PCRE风格的(?1$1:(?2"$2"))条件替换语法;
  3. 匹配逻辑冲突:原正则第二个分支\[([^\]]+)\]会优先匹配所有方括号内容,导致第一个匹配无空格内容的分支几乎无法触发。

修正后的C#实现

使用.NET正则引擎支持的MatchEvaluator委托实现条件替换,逻辑清晰且兼容:

using System.Text.RegularExpressions;

// 待处理的SQL字符串
string sql = @"CREATE TABLE [dbo].[Event](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Date Started] [datetime] NOT NULL,
    [StartTime] [time](7) NOT NULL,
    [Description] [nvarchar](250) NULL,
    [AudioLocation] [nvarchar](max) NOT NULL,
    [PlayerLocation] [nvarchar](max) NOT NULL,
 CONSTRAINT [PK_dbo.Event] PRIMARY KEY CLUSTERED";

// 匹配所有方括号包裹的内容,按需替换
string result = Regex.Replace(sql, @"\[([^\]]+)\]", match =>
{
    string content = match.Groups[1].Value;
    return content.Contains(" ") ? $"\"{content}\"" : content;
});

Console.WriteLine(result);

效果验证

运行上述代码后,输出结果与期望的目标格式完全一致:

CREATE TABLE dbo.Event(
    ID int IDENTITY(1,1) NOT NULL,
    "Date Started" datetime NOT NULL,
    StartTime time(7) NOT NULL,
    Description nvarchar(250) NULL,
    AudioLocation nvarchar(max) NOT NULL,
    PlayerLocation nvarchar(max) NOT NULL,
 CONSTRAINT PK_dbo.Event PRIMARY KEY CLUSTERED

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 05:05:32