Regex help: Split string into words AND double-quoted phrases

Discussion in 'Javascript' started by Robert Oschler, Aug 1, 2005.

  1. Can someone give me a regex expression that will split a sentence containing
    words and double-quoted phrases, into an array? I don't want the words
    between the double-quotes to be split using the space (or comma) character
    as a delimiter. I can do one or the other, tokenize the words or tokenize
    the double-quoted strings, but I can't figure out how to combine the two
    into the same regex expression. Note: I *do* want to capture (retain) the
    double-quotes.

    For example:

    > dogs cats and "other things".


    I want:

    1>dogs
    2>cats
    3>and
    4>"other things"

    not:

    1>dogs
    2>cats
    3>and
    4>"other
    5>things"

    Thanks.
     
    Robert Oschler, Aug 1, 2005
    #1
    1. Advertising

  2. Robert Oschler

    Baconbutty Guest

    Here is a rough go - still needs some work.

    Use the "|" union operator.

    The key I think is to put the expression for the "text in quotes" first
    in the union, so that the RegExp parser will grab that if it finds it
    first.

    function fTest()
    {
    var s='One two "three four" five six';

    var r=/(\"[^"]*\"|\w+)/g;

    s=s.replace(r,"$1|");

    a=s.split("|");

    alert(a);
    }
     
    Baconbutty, Aug 2, 2005
    #2
    1. Advertising

  3. Robert Oschler

    peterS. Guest

    hi Robert,


    Robert Oschler wrote:

    > Can someone give me a regex expression that will split a sentence containing
    > words and double-quoted phrases, into an array?
    > ...


    how about this one?

    var str = "dogs, cat and \"other things\".";
    var regX = /("[^"]+")|(\b\w+\b)/g;
    var arr = str.match(regX);
    alert((typeof arr.toSource == "function") ? (arr.toSource()) : (arr));


    so long - peterS.
     
    peterS., Aug 2, 2005
    #3
    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. =?Utf-8?B?RGF2aWQgVGhpZWxlbg==?=

    Does a resource have to have all phrases in it?

    =?Utf-8?B?RGF2aWQgVGhpZWxlbg==?=, Jan 30, 2006, in forum: ASP .Net
    Replies:
    4
    Views:
    378
    Neil Ni
    Feb 3, 2006
  2. Sydex
    Replies:
    12
    Views:
    6,505
    Victor Bazarov
    Feb 17, 2005
  3. oliver
    Replies:
    5
    Views:
    400
    Paul McGuire
    Mar 11, 2005
  4. pantagruel
    Replies:
    8
    Views:
    451
    Dr John Stockton
    Jul 22, 2006
  5. Cubicle Intern

    Querying words instead of phrases

    Cubicle Intern, Feb 29, 2008, in forum: Javascript
    Replies:
    2
    Views:
    127
    Tom de Neef
    Feb 29, 2008
Loading...

Share This Page