Rolling Your Own Expressions

Some standards organizations have published descriptions of exactly what makes up a legal value. Enterprising developers have transformed many of those descriptions into fairly portable regular expressions. Consider the following regular expression definition of a floating-point number:

^[+-]?[0-9]+[\.]?[0-9]*$

It’s not a perfect definition, but for many purposes, it’s a pretty good one—and a flexible one to boot. It accepts a pretty good range of floating-point numbers with optional signs at the start. Admittedly, as presented, it won’t accept –.75, but it will also not accept –., which I think offers a fair compromise because –0.75 isn’t too hard for the user to guess. Alternatively, you could use a set of regular ...

Get The Core iOS Developer’s Cookbook, Fifth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.