我需要在javascript中解析用户在html文本字段中输入的值。
这是我的第一次经验。
这是我的代码:
var s = 'research library "not available" author:"Bernard Shaw"';
var tableau = s.split(/(?:[^\s"]+|"[^"]*")/);
for (var i=0; i<tableau.length; i++) {
document.write("tableau[" + i + "] = " + tableau[i] + "<BR>");
}我希望能看到这样的景象:
tableau[0] = research
tableau[1] = library
tableau[2] = "not available"
tableau[3] = author:
tableau[4] = "Bernard Shaw"但我得到的却是:
tableau[0] =
tableau[1] =
tableau[2] =
tableau[3] =
tableau[4] =
tableau[5] = 实际上,我真正需要的是分割这个值:
research library "not available" author:"Bernard Shaw"在这个数组中:
tableau[0] = research
tableau[1] = library
tableau[2] = "not available"
tableau[3] = author:"Bernard Shaw"但我认为,在javascript或类似的东西中,积极的查找是有问题的。
我做了很多尝试,但没有取得更多的成功:
我真的需要一些帮助..。
发布于 2013-09-18 16:03:35
似乎你想在双引号之外的空格上分开。在这种情况下,您可以尝试这个正则表达式:
var tableau = s.split(/\s(?=(?:[^"]*"[^"]*")*[^"]*$)/);这将在空格上拆分,然后是偶数双引号。
解释:
\s # Split on whitespace
(?= # Followed by
(?: # Non-capture group with 2 quotes
[^"]* # 0 or more non-quote characters
" # 1 quote
[^"]* # 0 or more non-quote characters
" # 1 quote
)* # 0 or more repetition of previous group(multiple of 2 quotes will be even)
[^"]* # Finally 0 or more non-quotes
$ # Till the end (This is necessary)
) 这将给您最终想要的输出:
tableau[0] = research
tableau[1] = library
tableau[2] = "not available"
tableau[3] = author:"Bernard Shaw"发布于 2013-09-18 16:13:29
Regex可能不是该走的路。相反,您可以编写一个小的解析器,每次沿着一个字符前进并构建一个数组。如下所示(http://jsfiddle.net/WTMct/1):
function parse(str) {
var arr = [];
var quote = false; // true means we're inside a quoted field
// iterate over each character, keep track of current field index (i)
for (var i = c = 0; c < str.length; c++) {
var cc = str[c], nc = str[c+1]; // current character, next character
arr[i] = arr[i] || ''; // create a new array value (start with empty string) if necessary
// If it's just one quotation mark, begin/end quoted field
if (cc == '"') { quote = !quote; continue; }
// If it's a space, and we're not in a quoted field, move on to the next field
if (cc == ' ' && !quote) { ++i; continue; }
// Otherwise, append the current character to the current field
arr[i] += cc;
}
return arr;
}然后
parse('research library "not available" author:"Bernard Shaw"')返回["research", "library", "not available", "author:Bernard Shaw"]。
发布于 2013-09-18 16:17:40
您也可以匹配字符串。
var output=s.match(/"[^"]*"|\S+/g);https://stackoverflow.com/questions/18877020
复制相似问题