正则表达式匹配方括号内的括号内的数字和可选文本
首先,我在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+\)[^\]]*\]
可能需要更多的逃避?
怎么样“^ \ [\((d +)\)”(perl风格,不熟悉C#)。 我想你可以放心地忽略剩余的一行。
取决于你想要完成的事情……
List 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(mtchObj.Count); else rslt = new List (); 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 );