A Regular Expression For IRC Messages

March 02, 2013 — < 1 minute long

Designing an IRC bot and trying to parse incoming messages? Try this:

^(?:[:](\S+) )?(\S+)(?: (?!:)(.+?))?(?: [:](.+))?$

It matches to these groups:

  1. prefix, sans colon (e.g. m@m.net)
  2. type (PING, PRIVMSG, etc.)
  3. destination (#mychannel, mybuddymichael, etc.)
  4. message, sans colon.

So using Clojure’s re-matches, "PING :server.net" extracts to

["PING :server.net"

And ":m@m.net PRIVMSG #mychannel :Hiya, buddy." would extract to

[":m@m.net PRIVMSG #mychannel :Hiya, buddy."
 "Hiya, buddy."]

This regex is a fine-tuning of Matthew DeSantis’s IRC regex. Much thanks to him.