Reputation: 2112
I'm trying to find a way to spilt a string into single words OR phrases where the phrase is enclosed in quotes. For example:
javascript 'sql server' vbscript
would be split into:
I got help yesterday with this question which splits the string into single words using
/[-\w]+/g
I've been wrestling with the dark art of regular expressions and found this question which does a similar thing in php but even with the explanation it still doesn't make a great deal of sense to me (and doesn't work when I copy/paste into javascript!)
/"(?:\\\\.|[^\\\\"])*"|\S+/
Any help appreciated even a pointer to an easy to understand guide to regular expressions!
Upvotes: 0
Views: 147
Reputation: 422
try this:
var pattern = /('[^']+'|[-\w]+)/g;
var text = "javascript 'sql server' vbscript";
console.log(text.match(pattern));
Upvotes: 1
Reputation: 639
Maybe you could try this
var text = ...
var split = function(tx) {return tx.split("\'", }
This should split it along quotes. Then just use the length to figure it out, as all the even numbered indexes are quotes. Then join the odd indexes and do a split(" ")
to get the words
Upvotes: 0
Reputation: 11009
You should try the following:
/([-\w]+)|'([^']*)'/g
However, this is will fail if you have any form of single-quotes inside your quoted strings, that means, you cannot escape quotes with this construct.
Upvotes: 1