Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to match numbers inside parenthesis inside square brackets with optional text

Tags:

c#

regex

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?

like image 614
JC Grubbs Avatar asked Jun 17 '09 21:06

JC Grubbs


People also ask

How to match nested parentheses in regular expression?

If you need to match nested parentheses, you may see the solutions in the Regular expression to match balanced parentheses thread and replace the round brackets with the square ones to get the necessary functionality. You should use capturing groups to access the contents with open/close bracket excluded:

How to select text between two matching parentheses in a string?

If you want to select text between two matching parentheses, you are out of luck with regular expressions. This is impossible (*). This regex just returns the text between the first opening and the last closing parentheses in your string. (*) Unless your regex engine has features like balancing groups or recursion.

How to capture the innards of brackets in a group using regex?

If your regex engine does not support lookaheads and lookbehinds, then you can use the regex \ [ (.*?)\] to capture the innards of the brackets in a group and then you can manipulate the group as necessary. How does this regex work? The parentheses capture the characters in a group.

How to match numbers and number ranges in regular expressions?

Similarly the range [0-255] will match 0,1,2,5. First is the range 0-2 which is in a character class will match 0,1,2 and 5 written two times, will match 5. Now lets begin the logic and philosophy of matching numbers and number ranges in Regular expressions.


2 Answers

This should work:

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

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

\[\((\d+)\).*?\]
like image 110
molf Avatar answered Sep 22 '22 13:09

molf


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
}
like image 29
JP Alioto Avatar answered Sep 24 '22 13:09

JP Alioto