Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Javascript > Regex help: Split string into words AND double-quoted phrases

Reply
Thread Tools

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

 
 
Robert Oschler
Guest
Posts: n/a
 
      08-01-2005
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.



 
Reply With Quote
 
 
 
 
Baconbutty
Guest
Posts: n/a
 
      08-02-2005
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);
}

 
Reply With Quote
 
 
 
 
peterS.
Guest
Posts: n/a
 
      08-02-2005
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.

 
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 String.split to split a mixed encoding string(partencoded in gbk, part encoded in utf-8) Stanley Xu Ruby 2 03-23-2011 02:06 PM
Querying words instead of phrases Cubicle Intern Javascript 2 02-29-2008 10:59 PM
Replace stop words (remove words from a string) BerlinBrown Python 6 01-17-2008 02:37 PM
String#split(/\s+/) vs. String#split(/(\s+)/) Sam Kong Ruby 5 08-12-2006 07:59 PM
split camelcase string into array of words words pantagruel Javascript 8 07-22-2006 07:46 PM



Advertisments