-4

I want to find texts (using C#), in a string, that starts with the word "Column" and ends any number (for example "100").

In short, I want to find:

Column1
Column100
Column1000

But not to find:

Column_1
_Column1
Column1$

I can't find a way to do it, using regular expressions.

heijp06
  • 11,558
  • 1
  • 40
  • 60
Murat
  • 35
  • 7

2 Answers2

11

This is practically as easy as regular expressions get.

^Column\d+$
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Another way without Regex :

public string getColumnWithNum(string source)
{
     string tmp = source;
     if (tmp.StartsWith("Column"))
     {
          tmp.Replace("Column", "");
          UInt32 num
          if (UInt32.TryParse(tmp, out num)
          {
               return source; // matched
          }
     }
     return ""; // not matched
}

this should work.

aloisdg
  • 22,270
  • 6
  • 85
  • 105
  • 1
    True, but this type of problem is exactly why regular expressions were created in the first place. I know they get used for all sorts of things that don't suit them, but this not only suits them, it's what they're ***for***. – Corey Jan 23 '14 at 10:35
  • And this one is pretty easy to read but regex can be slow. If someone come here and dont want use it, he can use this alternative. – aloisdg Jan 23 '14 at 10:42
  • I was interested in the performance difference and the difference between the above code and a compiled Regex was that the Regex took 3% longer to run – Randy Levy Jan 23 '14 at 19:24
  • @Tuzo Good to now. Then, 3% is not a so big difference. – aloisdg Jan 23 '14 at 20:35
  • 1
    Actually, the 3% is in a small matched case (e.g. "Column1000"). For an unmatched case with a larger string (300 characters) then string approach was twice as slow as the Regex approach and the Regex took about 2/3rds the time as both in the matched case. So there are situations where the Regex performs much better. In either case, the absolute time is quite small and the time taken is probably much less than an application doing some other "real" work. – Randy Levy Jan 23 '14 at 20:40