0

If I have a strings like

[1] Bryan Mar

John Doe [2]

Mary [3] Cole

How would i get the value inside the [] if it is randomly located in each string.

I was thinking of regular expressions but I don't know how to create a pattern for this example.

Thanks for your help.

Update Numbers inside the [] is a 32bit integer

Philip Badilla
  • 1,038
  • 1
  • 10
  • 21

1 Answers1

1

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+)\].*$");
Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222