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

R

Robert Oschler

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.
 
B

Baconbutty

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);
}
 
P

peterS.

hi Robert,


Robert said:
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.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top