Pattern Matching With Regex in Scala

I’ve been spending quite a bit of time with Scala lately.  I continue to come across the same old problems that I’ve solved a million times in Java, but now Im trying to find ways to take advantage of Scala features to solve them differently.

For example, I needed to parse a number out of a string the other day.  A typical case where i had a namespaced value in a string delimited by a colon. ie. “<NS>:<Number>”

My initial instinct was to either use a regex with groups, or just split the string on the colon and pull out the second array member. Either of these solutions would have worked, and has worked countless times, but they each have their problems with correctness and verbosity.

BUT WAIT! I’m coding in Scala… there must be a better way right? There is:

My scala function uses regex groups to extract the namespace and id from the string.  If the pattern matches then it evaluates to the option Some(<id>), if it doesn’t match then it evaluates to None. Simple. Readable. Type safe.

Advertisements

Software Engineering Manager at Twitter Boston.

Tagged with: , , , , ,
Posted in Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Enter your email address to follow this blog and receive notifications of new posts by email.

%d bloggers like this: