C# 正则表达式匹配方括号内括号内的数字与可选文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1009633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regular Expression to match numbers inside parenthesis inside square brackets with optional text
提问by JC Grubbs
Firstly, I'm in C# here so that's the flavor of RegEx I'm dealing with. And here are thing things I need to be able to match:
首先,我在这里使用 C#,所以这就是我正在处理的 RegEx 的风格。这是我需要能够匹配的事情:
[(1)]
or
或者
[(34) Some Text - Some Other Text]
So basically I need to know if what is between the parentheses is numeric and ignore everything between the close parenthesis and close square bracket. Any RegEx gurus care to help?
所以基本上我需要知道括号之间的内容是否是数字,并忽略右括号和右方括号之间的所有内容。任何正则表达式大师关心帮助?
采纳答案by molf
This should work:
这应该有效:
\[\(\d+\).*?\]
And if you need to catch the number, simply wrap \d+
in parentheses:
如果您需要捕捉数字,只需\d+
用括号括起来:
\[\((\d+)\).*?\]
回答by Douglas Leeder
Something like:
就像是:
\[\(\d+\)[^\]]*\]
Possibly with some more escaping required?
可能需要更多的转义?
回答by JP Alioto
Do you have to match the []? Can you do just ...
你必须匹配[]吗?你能不能只...
\((\d+)\)
(The numbers themselves will be in the groups).
(数字本身将在组中)。
For example ...
例如 ...
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
}
回答by JP Alioto
How about "^\[\((d+)\)" (perl style, not familiar with C#). You can safely ignore the rest of the line, I think.
"^\[\((d+)\)" 怎么样(perl 风格,不熟悉 C#)。我认为,您可以放心地忽略该行的其余部分。
回答by JP Alioto
Depending on what you're trying to accomplish...
取决于你想完成什么......
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);
}
}
回答by Darryl
How's this? Assuming you only need to determine if the string is a match, and need not extract the numeric value...
这个怎么样?假设您只需要确定字符串是否匹配,而无需提取数值...
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 );
回答by James
Regex seems like overkill in this situation. Here is the solution I ended up using.
在这种情况下,正则表达式似乎有点矫枉过正。这是我最终使用的解决方案。
var src = test.IndexOf('(') + 1;
var dst = test.IndexOf(')') - 1;
var result = test.SubString(src, dst-src);