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

5

首先,我在使用C#,因此需要用到C#的正则表达式。以下是我需要匹配的内容:

[(1)]

或者

[(34) Some Text - Some Other Text]

基本上我需要知道括号内的内容是否为数字,并忽略右括号和右方括号之间的所有内容。 有没有正则表达式专家可以帮忙?

7个回答

17

这应该可以工作:

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

如果你需要捕获数字,只需在 \d+ 周围加上括号:

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

1
正则表达式在这种情况下似乎过于复杂。以下是我最终使用的解决方案。
var src = test.IndexOf('(') + 1;
var dst = test.IndexOf(')') - 1;
var result = test.SubString(src, dst-src);

一行代码和三行代码并不算过度。 - Archonic

1

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

\((\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
}

0

类似于:

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

也许需要一些更多的转义处理?


0

根据你想要实现的目标不同...

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);
    }
}

0
这个怎么样?假设你只需要确定字符串是否匹配,而不需要提取数字值...
        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 );

0

“^\[\((d+)\)”这个是 Perl 风格的正则表达式,不太熟悉 C#。你可以安全地忽略掉行中的其余部分。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接