c# – 正则表达式只能得到包含数字的方括号,但不在方括号内

示例字符串
"[] [ds*[000112]] [1448472995] sample string [1448472995] ***";

正则表达式应该匹配

[1448472995] [1448472995]

因为有外方括号,所以不应该匹配[000112].

目前我的这个正则表达式也匹配[000112]

const string unixTimeStampPattern = @"\[([0-9]+)]";

解决方法

这是使用平衡文本执行此操作的好方法.
( \[ \d+ \] )                 # (1)
 |                             # or,\[                            # opening bracket
    (?>                           # Then either match (possessively):
         [^\[\]]+                      #  non - brackets
      |                              # or
         \[                            #  [ increase the bracket counter
         (?<Depth> )
      |                              # or
         \]                            #  ] decrease the bracket counter
         (?<-Depth> )
    )*                            # Repeat as needed.
    (?(Depth)                     # Assert that the bracket counter is at zero
         (?!)
    )
    \]                            # Closing bracket

C#样本

string sTestSample = "[] [ds*[000112]] [1448472995] sample string [1448472995] ***";
Regex RxBracket = new Regex(@"(\[\d+\])|\[(?>[^\[\]]+|\[(?<Depth>)|\](?<-Depth>))*(?(Depth)(?!))\]");

Match bracketMatch = RxBracket.Match(sTestSample);
while (bracketMatch.Success)
{
    if (bracketMatch.Groups[1].Success)
        Console.WriteLine("{0}",bracketMatch);
    bracketMatch = bracketMatch.Nextmatch();
}

产量

[1448472995]
[1448472995]

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...