Hi guys,
yes it's another .net regex question :) (please excuse the long waffle leading up to the actual question)
I'm allowing users to use simple date/time macros for entering dates quickly (they don't want a date picker)
for example they can enter:
d +1d -2h
this will give them a date time string of todays's date, plus one day, minus two hours.
anyways I've created a regex to match these which works fine (probably not the best way to do it but it works!):
\b[DTdt]( *[+-] *[1-9][0-9]* *[dDhHmMwW])*\b
as you've probably guessed i'm using the regex to validate these entries before parsing them to calculate the resulting datetime. At first I used something like:
Regex rgxDateTimeMacro = new Regex(@"\b[DTdt]( *[+-] *[1-9][0-9]* *[dDhHmMwW])*\b");
if(rgxDateTimeMacro.isMatch(strInput)){
...string passes...
}
I then quickly realised that isMatch returns true if there's any matches in the passed string,
d +1d +1
would return true ^__^
so i changed it around to do something like this:
Regex rgxDateTimeMacro = new Regex(@"\b[DTdt]( *[+-] *[1-9][0-9]* *[dDhHmMwW])*\b");
MatchCollection objMatches = rgxDateTimeMacro.Matches(strInput);
if (objMatches.Count > 0)
{
// to pass.. we need a match which is the same length as the input string...
foreach (Match m in objMatches)
{
if (m.Length == strInput.Length)
{
...string passes...
}
}
}
now this works fine, but my question is this: is there a simpler way to check if a string (the whole string) matches a regex? I've had a google around, but cant seem to find an obvious answer.
hope this makes sense
Pete
UPDATE
thanks for all the quick answers, ^$ does the trick : )
(showing my inexperience with regexes ^__^)