C# 为何我不可以删除;[restr=戸;];用这个图案

C# 为何我不可以删除;[restr=戸;];用这个图案,c#,regex,C#,Regex,我有这样一根绳子: " [2][n] shutter; window shutter ,と|戸,1266970,(Y, 5, 3, Y, [1][n] [restr=戸] door (esp. Japanese-style)" 我正在尝试删除[rest]=戸] 使用此代码: Regex regex = new Regex(@"(\n )?\[(see|note|ant|restr|syn)=[^\]]*\]]"); var m1 = regex.Replace(m, "")

我有这样一根绳子:

"
[2][n]
  shutter; window shutter

,と|戸,1266970,(Y, 5, 3, Y, [1][n]
  [restr=戸]
  door (esp. Japanese-style)"
我正在尝试删除
[rest]=戸]

使用此代码:

 Regex regex = new Regex(@"(\n  )?\[(see|note|ant|restr|syn)=[^\]]*\]]");
 var m1 = regex.Replace(m, "");
但当我看m1时,弦仍然存在


有人知道为什么不删除字符串吗?

您需要删除最后一个
]
,因为它需要第二次关闭
]
,我还建议匹配CRLF或LF结尾(如果您可以使用Windows或Unix行结尾),并增强水平空白部分:

var m1 = Regex.Replace(m, @"(?:\r?\n[\p{Zs}\t]*)?\[(?:see|note|ant|restr|syn)=[^]]*]", "");

详细信息

  • (?:\r?\n[\p{Zs}\t]*)?
    -一个可选的
  • \[
    -a
    [
    字符
  • (?:参见| note | ant | rest | syn)
    -要么
    参见
    注释
    ant
    rest
    要么
    字符序列
  • =
    -a
    =
    字符
  • [^]]*
    -0个或更多字符,而不是
    ]
  • ]
    -一个
    ]
    字符

我的猜测是最好用一些简单的表达式,比如

\s*\[\s*\b(?:see|note|ant|restr|syn)\b\s*=[^\]]*\]
测试1 测试2 输出
如果您希望简化/修改/探索表达式,将在的右上面板中进行解释。如果您愿意,还可以在中查看它与一些示例输入的匹配情况


正则表达式电路 可视化正则表达式:

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"\s*\[\s*\b(?:see|note|ant|restr|syn)\b\s*=[^\]]*\]";
        string substitution = @"";
        string input = @"[2][n]
          shutter; window shutter

        ,と|戸,1266970,(Y, 5, 3, Y, [1][n]
          [restr=戸]
          door (esp. Japanese-style)";
        RegexOptions options = RegexOptions.Singleline;

        Regex regex = new Regex(pattern, options);
        string result = regex.Replace(input, substitution);
        Console.WriteLine(result);
    }
}
using System;
using System.Text.RegularExpressions;

public class Test
{
    public static void Main()
    {
        string pattern = @"(?s)\s*\[\s*\b(?:see|note|ant|restr|syn)\b\s*=[^\]]*\]";
        string substitution = @"";
        string input = @"[2][n]
          shutter; window shutter

        ,と|戸,1266970,(Y, 5, 3, Y, [1][n]
          [restr=戸]
          door (esp. Japanese-style)";
        Regex regex = new Regex(pattern);
        string result = regex.Replace(input, substitution);
        Console.WriteLine(result);
    }
}
[2][n]
  shutter; window shutter

,と|戸,1266970,(Y, 5, 3, Y, [1][n]
  door (esp. Japanese-style)