Jon said:
Yes, as there's TryParse, that's a good thing to use (it also means you
don't need to worry about allowing negatives - something we haven't
mentioned yet).
Again, a simpler solution than using regular expressions
If it has to be really fast (i.e. it's definitely an application
bottleneck) a hard-coded check is much faster (at least last time I did
some benchmarking) but for actual user input, efficiency probably
wasn't an issue.
I guess the speed difference could be partly due to the fact that you'd
code your own check more along the lines of your actual requirements,
while the Parse/TryParse methods include support for several formats, plus
culture specific things. Or were you saying they are badly coded?
I was assuming that "7." would be allowed (as it is by Double.Parse).
The OP really needs to work out exactly what he wants to allow
True. The "7." syntax doesn't add anything to the functionality though, so
I wouldn't see the purpose of supporting it.
That's true. Of course, you have to make sure you use the right dialect
of regular expressions - expressions that will work in .NET may not
work in Java and vice versa. (As far as I can see, that site doesn't
say which dialect any particular expression is designed for.)
This is usually only a problem with rather complicated stuff like zero
width assertions and similar things, where the syntax varies over
platforms. Actually, there's a POSIX standard for regular expressions -
but it's verbose and ugly, so it's not nice writing expressions to conform
with it.
When looking at such a library, it's probably best to find out what people
are focused on, so you can guess for which platform they're writing their
expressions. For example, if they're advertising Regulator on the front
page, .NET isn't too wild a guess ;-)
Of course, the hard-coded check would also be reusable...
I'd rather give someone a good regex - the problem of passing around code
snippets that do these kinds of checks is not the passing around in
itself. It's more the making small changes to adapt to the target
application that quickly breaks things.
Of course regexes break, too. But it's easy to post to a newsgroup with
your regex and a few sample inputs and get a good reply quickly. I like to
read posts like that, because they tend to be short and to the point. It's
much harder posting a complete code snippet with sample inputs in the
first place, and it's much harder to read such a post and help that person.
Oliver Sturm