Using Regular Expressions to Check String Length
Regular expressions are the ace up the sleeve of many of the most talented programmers out there. With a solid understanding of how regular expressions work, it’s sometimes possible to bypass a tangled mess of conditional logic and recursive function calls with a simple one-liner that just gets the job done much more efficiently.
One of the convenient places to use regular expressions is when doing form validation. With HTML5 it’s possible to enforce attributes like field length, but if someone tries to mess with your security and post values without using the form, you need to be able to verify that what you intended and what you’re getting are consistent.
To check the length of a string, a simple approach is to test against a regular expression that starts at the very beginning with a ^ and includes every character until the end by finishing with a $. You specify the number of characters you want to accept by putting that value inside curly braces right before the ‘$’ at the end.
For example, if I wanted a regular expression that had to consist of exactly seven letters, I might write a regular expression like this:
This will match a seven-letter string like ‘abcdefg’ but not any string longer or shorter than seven letters, and certainly not any string containing anything else but letters.
It might be more sensible for real users if I also included a lower limit on the number of letters. To do this, just add a lower value and a comma before the upper limit inside the curly braces:
Now any set of letters between three and seven letters will be matched.
If, on the other hand, I just wanted to set the lower limit, I could leave off the second value, as long as I included the comma:
Now a string of at least three letters, but extending to any length, and containing nothing other than letters, will be matched. Depending on your language, that could be a complicated proposition to test for without the convenience of regular expressions.
Learn how to use regular expressions in your coding, and you will start discovering a wide range of useful applications. They may look cryptic at first, but becoming adept with regular expressions will pay off in the long run.