• Status: Solved
• Priority: Medium
• Security: Public
• Views: 331

Regex: Can't match last space character

String txt has a space at the end.
string rx2 has a space at the end, rx1 does not.
``````      string txt = "2011-09-24 18:37:54.19 ";
string rx1 = "^20[0-9]{2}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]) (2[0-3]|[0-1][0-9]):[0-5][0-9]:[0-5][0-9]";
string rx2 = "^20[0-9]{2}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]) (2[0-3]|[0-1][0-9]):[0-5][0-9]:[0-5][0-9] ";
Regex r1 = new Regex(rx1);
Regex r2 = new Regex(rx2);
Match m1 = r1.Match(txt);
Match m2 = r2.Match(txt);
bool x1 = m1.Success;
bool x2 = m2.Success;
``````
x1 = True
x2 = False

Why can't I match that last space character?
0
deleyd
• 2
1 Solution

Commented:
Neither patten takes into account the fractional time (i.e. 19). The reason the first matches is because the pattern matches right up to the period before "19". That is enough to satisfy the pattern. When you added the space in rx2, you essentially stated that the period should be a space, which of course it is not. You need to account for the fractional time. Try these corrections:

``````string rx1 = "^20[0-9]{2}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]) (2[0-3]|[0-1][0-9]):[0-5][0-9]:[0-5][0-9]\\.\\d+";
string rx2 = "^20[0-9]{2}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]) (2[0-3]|[0-1][0-9]):[0-5][0-9]:[0-5][0-9]\\.\\d+ ";
``````
0

Commented:
The reason the first matches is because the pattern matches right up to the period before "19".
I should make clear that it matches up to, but not including, the period. So basically, up to the 4 in "54".
0

Author Commented:
:)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Featured Post

• 2
Tackle projects and never again get stuck behind a technical roadblock.