Write code deliberately, and pick the right tool for the job
String objects. This article aims to highlight two methods I see being used for checking strings for patterns, how they might be misused, and how you can use them appropriately.
This article assumes you understand what regular expressions are, how to infer their meaning, and when it’s appropriate to use them.
Problem: Write a function that takes a string and a pattern as its inputs and prints “Pattern Found” if the pattern is found in the string and “Pattern Not Found” otherwise.
Although masked in simplicity and maybe even triviality, developers frequently encounter problems similar to this one — a problem where we must check that a string contains a certain pattern and write code that does one thing when the pattern is found and take another course of action when the pattern is absent from the string. We encounter this problem so often that we develop a solution that sits ready to be pulled out of our left brains at a moment’s notice.
Pick the right tool for the job
“Pick the right tool for the job” is a sentence we hear a lot in industry, and I suspect many of us really try to abide. I hear this sentence most frequently used when addressing the macro solution to a problem, for example, in using an appropriate software package or in choosing an appropriate software development methodology. Now, I am making the same recommendation to pick the right tool for the job at the micro level (in code), because it matters there too.
If the string matches the expression, it will return an
Arraycontaining the entire matched string as the first element, followed by any results captured in parentheses. If there were no matches,
trueif there is a match between the regular expression and the specified string; otherwise,
The first solution works because if the pattern is found, the returned array will evaluate to
true in the
if statement and
null is return due to the absence on the pattern in the string.
match was not designed to simply and efficiently check if a pattern is found in a string. Anticipating the misuse of
match, the Mozilla Developer Network documents,
If you need to know if a string matches a regular expression
Finally, we can intuit that
match performs slower than
test. Just imagine the extra work being done to build up an array of all the matched substrings as opposed to returning a single value on the first occurrence of a match. Still don’t believe me? Take a look at how much faster
test is than
match here. It’s much faster!
test to do a simple boolean check for whether or not a pattern exists in a string and
match to build up an array of the matches found in the string. When it comes to solving problems with code, picking the right tool for the job is just as important in the micro as it is in the macro.