[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Split a sentence by regular expression

Pranjal Jain

4/26/2008 9:01:00 AM

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[i]
#~ if (matching[i] == "u")
#~ puts "Who is Anant?"
#~ end
i +=1

end

"
--
Posted via http://www.ruby-....

1 Answer

Peter Szinek

4/26/2008 9:07:00 AM

0

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.rubyra...
http://s...


On Apr 26, 2008, at 11:00 AM, Pranjal Jain wrote:

> 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[i]
> #~ if (matching[i] == "u")
> #~ puts "Who is Anant?"
> #~ end
> i +=1
>
> end
>
> "
> --
> Posted via http://www.ruby-....
>