tags:

views:

105

answers:

6

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:

[(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?

+4  A: 

This should work:

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

And if you need to catch the number, simply wrap \d+ in parentheses:

\[\((\d+)\).*?\]
molf
A: 

Something like:

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

Possibly with some more escaping required?

Douglas Leeder
A: 

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
}
JP Alioto
A: 

How about "^\[\((d+)\)" (perl style, not familiar with C#). You can safely ignore the rest of the line, I think.

Arkadiy
A: 

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);
    }
}
Tim
A: 

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