Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > Split a sentence by regular expression

Reply
Thread Tools

Split a sentence by regular expression

 
 
Pranjal Jain
Guest
Posts: n/a
 
      04-26-2008
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-forum.com/.

 
Reply With Quote
 
 
 
 
Peter Szinek
Guest
Posts: n/a
 
      04-26-2008
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


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-forum.com/.
>



 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
How to use regex to split a sentence with different spaces? www Java 2 01-30-2007 09:49 PM
Perl Split on a Long Sentence Question Brian Wilkins Perl Misc 2 10-09-2006 05:01 PM
Regular expression to split on . PC Perl 3 04-24-2005 01:41 PM
Split a sentence by punctuations using Python chad Python 2 03-05-2004 11:07 PM
Dynamically changing the regular expression of Regular Expression validator VSK ASP .Net 2 08-24-2003 02:47 PM



Advertisments