Split a sentence by regular expression

Discussion in 'Ruby' started by Pranjal Jain, Apr 26, 2008.

  1. Pranjal Jain

    Pranjal Jain Guest

    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

    "
    --
    Posted via http://www.ruby-forum.com/.
    Pranjal Jain, Apr 26, 2008
    #1
    1. Advertising

  2. Pranjal Jain

    Peter Szinek Guest

    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
    > #~ if (matching == "u")
    > #~ puts "Who is Anant?"
    > #~ end
    > i +=1
    >
    > end
    >
    > "
    > --
    > Posted via http://www.ruby-forum.com/.
    >
    Peter Szinek, Apr 26, 2008
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. PC
    Replies:
    3
    Views:
    2,645
    Alex I. Varyanick
    Apr 24, 2005
  2. VSK
    Replies:
    2
    Views:
    2,272
  3. chad
    Replies:
    2
    Views:
    1,323
    Peter Otten
    Mar 5, 2004
  4. www
    Replies:
    2
    Views:
    696
    Andreas Leitgeb
    Jan 30, 2007
  5. Brian  Wilkins

    Perl Split on a Long Sentence Question

    Brian Wilkins, Oct 9, 2006, in forum: Perl Misc
    Replies:
    2
    Views:
    89
    -berlin.de
    Oct 9, 2006
Loading...

Share This Page