Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

special string splitting in Ruby

Tags:

split

ruby

I am trying to figure out the best way to do this...

Given a string

s = "if someBool || x==1 && y!=22314" 

I'd like to use Ruby to seperate statements and boolean operators.. so I'd like to split this into

["if","someBool","||","x","==","1","&&","y","!=","22314"]

I could use s.split(), but this only splits with space as delimeters..but I'd like x!=y to be split too (they are valid boolean sentences, they just dont have space in between for good readability). Of course the easiest way is to require the user to put space between boolean operator and variables, but are there any other way to do this?

like image 239
Jose Avatar asked Mar 04 '10 12:03

Jose


3 Answers

Split on whitespace or a word boundary:

s = "if someBool || x==1 && y!=22314"
a = s.split( /\s+|\b/ );
p a

Output:

["if", "someBool", "||", "x", "==", "1", "&&", "y", "!=", "22314"]
like image 55
FMc Avatar answered Sep 30 '22 16:09

FMc


My rule of thumb: use split if you know what to throw away (the delimiters), use a regex if you know what to keep. In this case you know what to keep (the tokens), so:

s.scan(/ \w+ | (?: \s|\b )(?: \|\| | && | [=!]= )(?: \s|\b ) /x)
# => ["if", "someBool", "||", "x", "==", "1", "&&", "y", "!=", "22314"]

The (?: \s|\b ) "delimiters" are to prevent your tokens (e.g. ==) from matching something you don't want (e.g. !==)

like image 44
glenn jackman Avatar answered Sep 30 '22 18:09

glenn jackman


Something like this works:

s = "12&&32 || 90==12 !=67"
a = s.split(/ |(\|\|)|(&&)|(!=)|(==)/)
a.delete("")
p a

For some reason "" remained in the array, the delete line fixed that.

like image 40
monoceres Avatar answered Sep 30 '22 17:09

monoceres