繁体   English   中英

正则表达式匹配方括号内括号内的数字和可选文本

[英]Regular Expression to match numbers inside parenthesis inside square brackets with optional text

首先,我在这里是 C#,这就是我正在处理的 RegEx 的风格。 以下是我需要匹配的东西:

[(1)]

要么

[(34) Some Text - Some Other Text]

所以基本上我需要知道括号之间的内容是否是数字,并忽略右括号和右方括号之间的所有内容。 任何 RegEx 专家愿意提供帮助吗?

这应该工作:

\[\(\d+\).*?\]

如果您需要获取数字,只需将\d+括在括号中即可:

\[\((\d+)\).*?\]

你必须匹配[]吗? 你能不能只...

\((\d+)\)

(数字本身将在组中)。

例如...

var mg = Regex.Match( "[(34) Some Text - Some Other Text]", @"\((\d+)\)");

if (mg.Success)
{
  var num = mg.Groups[1].Value; // num == 34
}
  else
{
  // No match
}

在这种情况下,正则表达式似乎有点矫枉过正。 这是我最终使用的解决方案。

var src = test.IndexOf('(') + 1;
var dst = test.IndexOf(')') - 1;
var result = test.SubString(src, dst-src);

就像是:

\[\(\d+\)[^\]]*\]

可能还需要一些 escaping?

"^\[\((d+)\)" 怎么样(perl 风格,不熟悉 C#)。 我认为您可以安全地忽略该行的 rest。

取决于你想要完成什么......

List<Boolean> rslt;
String searchIn;
Regex regxObj;
MatchCollection mtchObj;
Int32 mtchGrp;

searchIn = @"[(34) Some Text - Some Other Text] [(1)]";

regxObj = new Regex(@"\[\(([^\)]+)\)[^\]]*\]");

mtchObj = regxObj.Matches(searchIn);

if (mtchObj.Count > 0)
    rslt = new List<bool>(mtchObj.Count);
else
    rslt = new List<bool>();

foreach (Match crntMtch in mtchObj)
{
    if (Int32.TryParse(crntMtch.Value, out mtchGrp))
    {
        rslt.Add(true);
    }
}

这个怎么样? 假设您只需要确定字符串是否匹配,而不需要提取数值...

        string test = "[(34) Some Text - Some Other Text]";

        Regex regex = new Regex( "\\[\\(\\d+\\).*\\]" );

        Match match = regex.Match( test );

        Console.WriteLine( "{0}\t{1}", test, match.Success );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM