Kotlin Code Smell 29 - Regular Expression Abusers

Kotlin Code Smell 29 - Regular Expression Abusers

From Spaghetti Code to Readable Magic

RegEx is a wonderful tool, we should use them carefully and not look smart.


  • Readability

  • Maintainability

  • Testability

  • Intention Revealing


  1. Use regular expressions just for string validation.

  2. If you need to manipulate objects, don't make them strings.

Sample Code


val regex = "^\\+(?:[0-9a-zA-Z][– -]?){6,14}[0-9a-zA-Z]$".toRegex()


val prefix = """\+"""
val digit = "[0-9a-zA-Z]"
val space = "[– -]"
val phoneRegex = "^$prefix(?:$digit$space?){6,14}$digit$".toRegex()


Regular expressions are a great tool for string validation. We must use them in a declarative way and just for strings.

Names are very important to understand pattern meanings.

If we need to manipulate objects or hierarchies, we should do it in an object way.

Unless we have a conclusive benchmark of impressive performance improvement.