Programming with Falcon: Regex

While programming with Falcon your almost always going to want to do something fun. I personally get tired of the stupid posts over and again about how to use strings

// Standard string
ex_str = "this is a string"
// String addition (concat)
ex_str + " ...and still is" = "this is a string ...and still is"
// Literal strings
lit_str = 'Hell I''m a literal string'  // notice the two single quotes to produce one single quote when outputed
// And even funny things like getting "d" from "a"
letter_from_letter = "a" / 3 = "d"

But personally, that kind of stuff bores me. Everybody can do that with just about any language. What about something more interesting? Like regex?

Regex

Let’s say you want to use Regex in your code. Why? I don’t know why you want regex. I don’t really care to be totally honest. And, of course, I’m really bad at coming up with examples. So, let’s use some regular expressions


#!/usr/bin/env falcon
load regex

string = "1234"

if string == Regex("/\d+/")
> "Found it!"
end

The above does basically what you’d expect. If the string contains a series of integers your good to go! But Falcon can do more and better. You can actually create regular expression objects:


#!/usr/bin/env falcon
load regex

string = "1234"
re = Regex("/\d+/")

if re.match( string )
> "Found it!"
// Note here I use printl so I don't have to worry about
// the type returned by re.captured
printl( "I found it, here: ", re.captured(1))
end

Now that is where it starts to become interesting for me. The examples are obviously trivial, but the you can begin the see the power of language forming. Now you can reuse and abuse not to mention your code becomes much cleaner. You might gain a line or two but the power and beauty you get from it are totally worth it.

Enjoy the Penguins!

About these ads
This entry was posted in falconpl and tagged . Bookmark the permalink.

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 )

Connecting to %s