Split a sentence by regular expression

P

Pranjal Jain

Hi
I want to split a sentence by means of regular expression.
For example, the sentence is
" Hello how r u?"

How can i split this ?

the way I used is as follows :

"

matching = Array.new
a = gets
puts a.split.length


re = /((\w+)\s)+/
matching = re.match(a)
i = 1
until i >a.split.length

puts i
puts matching
#~ if (matching == "u")
#~ puts "Who is Anant?"
#~ end
i +=1

end

"
 
P

Peter Szinek

What does "split a sentence" mean? If it's just split around spaces,
you could simply do

" Hello how r u?".split(' ')

or

" Hello how r u?".split(/\s+/)

if you want to remove empty words (i.e. ""s) you could do something like

" Hello how r u?".split(/\s+/).reject{|w| w == ""}

Does this answer your question?

Cheers,
Peter
___
http://www.rubyrailways.com
http://scrubyt.org
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,044
Latest member
RonaldNen

Latest Threads

Top