You are right that using a regular expression would be a one way to solve it. Try this:
class Program
{
static void Main(string[] args)
{
var strings = new string[] { "[1] Bryan Mar", "John Doe [2]", "Mary [3] Cole" };
var re = new Regex(@"^.*\[(\d)\].*$");
foreach (var s in strings)
{
var m = re.Match(s);
if (m.Success)
{
Console.WriteLine(m.Groups[1].Value);
}
}
Console.ReadLine();
}
}
The expression matches zero or more characters followed by an opening square bracket, followed by a single digit (\d
) and a closing square bracket and then any number of characters. The enclosing parenthesis adds the captured digit to a regular expression group which can be accessed later (in m.Groups[1]
). If you wonder why the group has index 1
and not index 0
, it is because the entire string is always group 0
.
If you want it to be able to match more than one digit, simply change the expression to:
var re = new Regex(@"^.*\[(\d+)\].*$");