Note that there are some explanatory texts on larger screens.

plurals
  1. PO.NET Regex isMatch vs Matches question
    text
    copied!<p>yes it's <em>another</em> .net regex question :) (please excuse the long waffle leading up to the actual question)</p> <p>I'm allowing users to use simple date/time macros for entering dates quickly (they don't want a date picker)</p> <p>for example they can enter:<br> <code>d +1d -2h</code><br> this will give them a date time string of todays's date, plus one day, minus two hours.</p> <p>anyways I've created a regex to match these which works fine (probably not the best way to do it but it works!):<br> <code>\b[DTdt]( *[+-] *[1-9][0-9]* *[dDhHmMwW])*\b</code></p> <p>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:</p> <pre><code>Regex rgxDateTimeMacro = new Regex(@"\b[DTdt]( *[+-] *[1-9][0-9]* *[dDhHmMwW])*\b"); if(rgxDateTimeMacro.isMatch(strInput)){ ...string passes... } </code></pre> <p>I then quickly realised that isMatch returns true if there's <em>any</em> matches in the passed string,<br> <code>d +1d +1</code><br> would return true ^__^</p> <p>so i changed it around to do something like this:</p> <pre><code>Regex rgxDateTimeMacro = new Regex(@"\b[DTdt]( *[+-] *[1-9][0-9]* *[dDhHmMwW])*\b"); MatchCollection objMatches = rgxDateTimeMacro.Matches(strInput); if (objMatches.Count &gt; 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... } } } </code></pre> <p>now this works fine, but my question is this: is there a simpler way to check if a string (the <em>whole</em> string) matches a regex? I've had a google around, but cant seem to find an obvious answer.</p> <p>hope this makes sense</p> <p>Pete</p> <hr> <p>UPDATE</p> <p>thanks for all the quick answers, ^$ does the trick : ) </p> <p>(showing my inexperience with regexes ^__^)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload