首先,我在使用C#,因此需要用到C#的正则表达式。以下是我需要匹配的内容:
[(1)]
或者
[(34) Some Text - Some Other Text]
基本上我需要知道括号内的内容是否为数字,并忽略右括号和右方括号之间的所有内容。 有没有正则表达式专家可以帮忙?
这应该可以工作:
\[\(\d+\).*?\]
如果你需要捕获数字,只需在 \d+
周围加上括号:
\[\((\d+)\).*?\]
var src = test.IndexOf('(') + 1;
var dst = test.IndexOf(')') - 1;
var result = test.SubString(src, dst-src);
你必须匹配 [] 吗?你能只做...
\((\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
}
类似于:
\[\(\d+\)[^\]]*\]
也许需要一些更多的转义处理?
根据你想要实现的目标不同...
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 );
“^\[\((d+)\)”这个是 Perl 风格的正则表达式,不太熟悉 C#。你可以安全地忽略掉行中的其余部分。