Regex

Regular expressions are hard, today framework doesn’t make them easier, but at least provides a nice Swift syntax around them.

Regex by Adam Sharp is another great example of small sharp focused (no pun intended) Swift library that does only one thing, but well. The author defines it a µframework.

Regex provides a swifty APIs around Foundation’s NSRegualrExpression. Let’s see some example usages of Regex

How to validate an input against a Regex

let input = "a pile of poo"

if Regex("(poo|poop)").matches(input) {
  print("Sorry you cannot use banned words")
}

How to access the captured matches of a regex

let dirtyString = "There is a lot of poo in this place"
let bannedRegexString = "(poo|poop)"

Regex(bannedRegexString).match(dirtyString)?.captures.forEach { captured in
  print("Sorry the word \(captured) is not allowed")
}

And finally, pattern matching like a boss

switch someTextFromTheInternet {
case Regex("DROP DATABASE (.+)"):
  // TODO: patch security hole
default:
  break
}

I hope this little tutorial on this little library showed you something useful you could leverage in your next projects, but also motivated you to create similar microframewors.


That’s it for today. See you tomorrow with the ultimate JSON parsing library. Subscribe to the email list to avoid missing out.

If you found this post useful and want to support the Advent Calendar please consider sharing it on your favourite social network. Thanks 🎅