Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby String split with regex

Tags:

This is Ruby 1.8.7 but should be same as for 1.9.x

I am trying to split a string for example:

a = "foo.bar.size.split('.').last" # trying to split into ["foo", "bar","split('.')","last"] 

Basically splitting it in commands it represents, I am trying to do it with Regexp but not sure how, idea was to use regexp

a.split(/[a-z\(\)](\.)[a-z\(\)]/) 

Here trying to use group (\.) to split it with but this seems not to be good approach.

like image 603
Haris Krajina Avatar asked Oct 11 '12 12:10

Haris Krajina


People also ask

How do you split a string in Ruby?

split is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified. Here the pattern can be a Regular Expression or a string. If pattern is a Regular Expression or a string, str is divided where the pattern matches.

What is regular expression in Ruby?

A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings using a specialized syntax held in a pattern.

How do I convert a string to an array in Ruby?

The general syntax for using the split method is string. split() . The place at which to split the string is specified as an argument to the method. The split substrings will be returned together in an array.


1 Answers

I think this would do it:

a.split(/\.(?=[\w])/) 

I don't know how much you know about regex, but the (?=[\w]) is a lookahead that says "only match the dot if the next character is a letter kind of character". A lookahead won't actually grab the text it matches. It just "looks". So the result is exactly what you're looking for:

> a.split(/\.(?=[\w])/)  => ["foo", "bar", "size", "split('.')", "last"]  
like image 165
Jason Swett Avatar answered Nov 21 '22 06:11

Jason Swett