Search code examples
c#regexbrackets

Remove square matching brackets but only those which do not have a white space inside bracket


Having looked at this answer: Remove square brackets if content within the square bracket does not contain spaces

This works fine for Notepad++ but when I take the Notepad++ solution and put it in C# I get all sorts of bad string replacements.

I have this now:

C# looks like this:

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

So if I have this:

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

I want to remove only the unnecessary brackets and get this:

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

Solution

  • I believe that replacing just at once is not a necessary requirement for this question. Why not just use Regex.Replace twice:

    using System;
    using System.Text.RegularExpressions;
                        
    public class Program
    {
        public static void Main()
        {
            string str = 
                @"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 pattern = @"\[([\w.]+)\]";
            str = Regex.Replace(str, pattern, "$1");
    
            pattern = @"\[(.+)\]"; 
            // or as per the suggestion in the comment below: pattern = @"\[([^\]]+)\]";
            str = Regex.Replace(str, pattern, "\"$1\"");
    
            Console.WriteLine(str);
        }
    }
    

    First replaces [ID], [int], [PK_dbo.Event] etc. Second - [Date Started].