Topic: Need help with scan syntax please

I'm trying to parse my tags for my view template.  Right now the issue is that the tag can be one word (table) or a phrase (new york)  so in the case of a my tag string:

a = 'new york' table '17th street'

I want to scan so that the results I get are:

new york, table, 17th street

Using a=st.scan(/\w+/) gives me new, york, table, 17th, street

Is there any way to alter the scan statement above to give me what I need?  Else is there another suggested method? 

Thanks in advance..

Re: Need help with scan syntax please

would it be difficult if you just seperate each tag with a comma?

if you want/have to use the style you wrote obove, you can get
the tags in the single quote with this command:
a = "'new york' table '17th street'"
a.scan(/'(.*?)'s*/ ).flatten
will result:
["new york", "17th street"]

I hope this can help you a bit.

My homepage: http://www.komendera.com/
Working at: http://www.abloom.at/
My blog: soaked and soaped http://soakedandsoaped.com/

Re: Need help with scan syntax please

Try this:

text = "'new york' table '17th street'"
tags = text.scan(/'(.+?)'|(\w+)/).flatten.compact
# => ["new york", "table", "17th street"]

If you need to support double quotes too you can do:

tags = text.scan(/['"](.+?)['"]|(\w+)/).flatten.compact

Last edited by ryanb (2006-08-15 19:14:23)

Railscasts - Free Ruby on Rails Screencasts

Re: Need help with scan syntax please

ryanb wrote:

Try this:

text = "'new york' table '17th street'"
tags = text.scan(/'(.+?)'|(\w+)/).flatten.compact
# => ["new york", "table", "17th street"]

If you need to support double quotes too you can do:

tags = text.scan(/['"](.+?)['"]|(\w+)/).flatten.compact

Perfect!  Thanks!  I wish I knew how to come up with that myself.. where does one learn how to decipher that syntax?

I was trying this:
<%a=st.scan(/\w+/)%>
<% for ab in a %>
<% zz = st.index(' ').to_i %>
<% jj = st.delete(' ')%>
<% rr=jj.scan(/\w+/)%>
<% ss = rr%>
<% end %>

which got me closer.. just had to figure out how to re-insert the space.  But your solution is way way better.  Thank you!

Re: Need help with scan syntax please

I'll see if I can break it down.

text.scan(/'(.+?)'|(\w+)/).flatten.compact

First we have the pipe down the middle which does an "or" search. For example /foo|bar/ will match foo or bar. On the left of the pipe it matches a pair of quotes (the question mark in .+? means don't do a greedy search so it will match any character until it reaches a single quote). The parenthesis in the expression tells scan what to return so the quotes aren't included. The results are all grouped together with flatten and the nils (unmatched parentheses) are removed with compact.

See this site for more information on regular expressions.

Last edited by ryanb (2006-08-15 20:55:14)

Railscasts - Free Ruby on Rails Screencasts