开发者

Splitting a Quoted Search String with Regular Expressions

I'm trying to figure out how to split a string into searchable terms. I need it to

  • split on spaces and single quotes (ignoring single character, non-quoted results)
  • return quoted phrases without the quotes

So if I'm applying it to: "quoted phras开发者_运维知识库e" single words It would return

  • quoted phrase
  • single
  • words

Here's what I have so far (in Javascript), but I have to have to strip the quotes out separately.

var searchArray = temp.match(/"[^"]*"|[^\s']{2,}/g);
for (index in searchArray)
    searchArray[index] = searchArray[index].replace(/"/g, '');

Is there any way to do this using only one regular expression?


This seems to work but I'm not sure I've covered all cases. I'm not sure it'll work in IE 5, but that may not worry you; it works in IE 6 and all other browsers I've tried. It also strips leading and trailing whitespace from matches inside quotes:

var regex = /("?)\s*\b(\S[^\1]*?)\b\s*\1/g;
var str = '"quoted phrase " single "quoted" words " yes "';
var res;

while ( (res = regex.exec(str)) ) {
    alert(res[2]);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜