I was wondering if there are any general guidelines for when to use regex VS "string".contains("anotherString")
and/or other String API calls?
While above given decision for .contains()
is trivial (why bother with regex if you can do this in a single call), real life brings more complex choices to make. For example, is it better to do two .contains()
calls or a single regex?
My rule of thumb was to always use regex, unless this can be replaced with a single API call. This prevents code against bloating, but is probably not so good from code readability point of view, especially if regex tends to get big.
Another, often overlooked, argument is performance. How do I know how many iterations (as in "Big O") does this regex require? Would it be faster than sheer iteration? Somehow everybody assumes that once regex looks shorter than 5 if
statements, it must be quicker. But is this always the case? This is especially relevant if regex cannot be pre-compiled in advance.