看过这个答案:如果方括号内的内容不包含空格,请删除方括号
这对于 Notepad++ 来说效果很好,但是当我将 Notepad++ 解决方案放入 C# 中时,我得到了各种错误的字符串替换。
我现在有这个:
C# 看起来像这样:
str.Regex.Replace(str, @"[(\w+)]|[([^]]+)]"), "(?1$1:(?2"$2"))")
所以如果我有这个:
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
这样的东西应该有效:
public static string RemoveBracketsIfSingleWord(string inputString)
{
// Regex pattern to match single words enclosed in square brackets without whitespace
string pattern = @"\[([^\]\s]+)\]";
// Replace matches with the captured word without brackets
return Regex.Replace(inputString, pattern, "$1");
}
您可以按如下方式调用此方法:
string s =
""""
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
"""";
Console.WriteLine(RemoveBracketsIfSingleWord(s));
我使用插值字符串来获得看起来不乱码的多行文本。
代码是不言自明的。