Tuesday, May 29, 2007

Ruby Regular Expressions

Aha, another quick lesson learned.  In Ruby, the regular expression is an object unto itself with its own syntax.  So to do a simple search and replace you do something like this:

"The quick brown fox".gsub /brown/, "purple"

which replaces the results of a match with regular expression "brown" with the string "purple".

But what if you wanted to do something more dynamic, like, say, matching a color based on a variable?  You can just as easily do this:

color="brown"

"the quick brown fox".gsub color, "purple"

And it will work.  Ay, though, but here's the rub -- it's no longer matching it as a regular expression.  Try this test:

input = "start:   data"

data = input.gsub! "start:( +)", ""

that should strip off the start: as well as one or more spaces, right? Nope.  It fails to match.  That's because since I'm passing a string it's not evaluating it as a regular expression.

Wrap that first element in a constructor for Regexp:    Regexp.new("start:( +)")  and you'll get the right answer.

 

Technorati tags: ,

2 comments:

steveo said...

What if you did:
color=/brown/

I'm not sure about ruby, but in perl and javascript you can use backslash delims to make a literal a regex literal rather than a string literal. Ruby is probably simialar.

Wolf said...

Regular expression is really wonderful to parsing HTML or matching pattern. I use this a lot when i code. Actually when I learn any new langauge, first of all I first try whether it supports regex or not. I feel ezee when I found that.

http://icfun.blogspot.com/2008/04/ruby-regular-expression-handling.html

Here is about ruby regex. This was posted by me when I first learn ruby regex. So it will be helpfull for New coders.