tags:

views:

24

answers:

1

I have a string which may contain cell address, which is look like:
A1, B34, Z728 - only capital letters and
AA3, ABA92, ZABC83 - there may be several letters before Integer number.
The typical source string is look like:
=3+7*A1-B3*AB28
I need to get collection of all cells in the string: A1, B3, AB28
I tried to use Regex.Matches method with the following regular expression: @"[A..Z]+?[1..9]+?", but it doesn't work. Can anybody help me to write the regular expression?

+5  A: 

There are three errors in your regular expression:

  • Character class ranges are specified with -, not ...
  • Cell addresses can contain the digit 0, just not as the first digit.
  • The greedy default is what you want. Your lazy matching will lose digits from the end.

Try this:

"[A-Z]+[1-9][0-9]*"

Example:

    string input = "3+7*A1-B3*AB28";
    foreach (Match match in Regex.Matches(input, "[A-Z]+[1-9][0-9]*"))
        Console.WriteLine(match.Value);

Output:

A1
B3
AB28
Mark Byers