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

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

概述示例字符串 "[] [ds*[000112]] [1448472995] sample string [1448472995] ***"; 正则表达式应该匹配 [1448472995] [1448472995] 因为有外方括号,所以不应该匹配[000112]. 目前我的这个正则表达式也匹配[000112] const string unixTimeStampPattern = @"\[([0-9] @H_404_1@示例字符串
"[] [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]
总结

以上是内存溢出为你收集整理的c# – 正则表达式只能得到包含数字的方括号,但不在方括号内全部内容,希望文章能够帮你解决c# – 正则表达式只能得到包含数字的方括号,但不在方括号内所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1252352.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存