tags:

views:

54

answers:

3

I have string for example: 06.07.2010 (tor.)

I would like to extract only 06.07.2010 using a regex, but the following is not working correctly:

^([0-9]{1,2}).([0-9]{1,2}).([0-9]{4,4})$
^([1-9]|0[1-9]|[12][0-9]|3[01])[- /.]([1-9]|0[1-9]|1[012])[- /.][0-9]{4}$

Can someone tell me what is wrong here?

+3  A: 

It's the $ at the end. It means there can't be any characters after the year digits - in other words, the RE has to match the entire string.

You probably want this instead:

^([0-9]{1,2}).([0-9]{1,2}).([0-9]{4,4})
Richard Fearn
it's probably good idea to replace dots with [- /.] like done in second example, or at least escape them.
repka
True - I saw the other comment about escaping the dots (before it was deleted). But that wasn't the reason for the RE not matching the string that has "(tor.)" at the end.Of course, not escaping the dot may be intentional - to allow it to match other separators, like dashes.
Richard Fearn
uh thx forget about $ at the end of regex. My mistake. Tha all again.
senzacionale
+1  A: 

Maybe there's more going on than what you say or the incoming string can be more complex, but why not just use String.Split? It's much more clear IMO.

string dateAndStuff = "06.07.2010 (tor)";
string[] parts = dateAndStuff.Split(' ');

if(parts.Length > 0)
{
  string date = parts[0];
  if(!string.IsNullOrEmpty(date)) //use date
}
Chad
+1 RegEx are overrated.
CesarGon
A: 

The problem is that you are specifying that the end of the string ($) should follow immediately after the year. If you remove that condition, you will be able to get the date from the string. Also you are catching the components separately, so you won't get the date as a single string. Also, you need to escape the periods if you want them to match only periods, otherwise they will match any character:

^([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{4,4})

or simply:

^(\d{1,2}\.\d{1,2}\.\d{4})
Guffa
Why the downvote? If you don't explain what it is that you think is wrong, it can't improve the answer.
Guffa