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?
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:
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.
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.
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.
This should work:
\[\(\d+\).*?\]
And if you need to catch the number, simply wrap \d+
in parentheses:
\[\((\d+)\).*?\]
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With