73

[a, b, c, "d, e, f", g, h]a、b、c、 "d、e、f"、g、hの6つの要素の配列に変換することを探しています。私はJavascriptを介してこれを行おうとしています。これは私がこれまでに持っているものです:

str = str.split(/,+|"[^"]+"/g); 

しかし、現在、二重引用符で囲まれているものはすべて分割されていますが、これは正しくありません。

編集:申し訳ありませんが、私はこの質問の言い回しが非常に貧弱でした。配列ではなく文字列が与えられています。

var str = 'a, b, c, "d, e, f", g, h';

そして、「分割」関数のようなものを使用して、それを配列に変換したいと思います。

4

17 に答える 17

98

これが私がすることです。

var str = 'a, b, c, "d, e, f", g, h';
var arr = str.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g);

ここに画像の説明を入力 /* 一致します:

    (
        ".*?"       double quotes + anything but double quotes + double quotes
        |           OR
        [^",\s]+    1 or more characters excl. double quotes, comma or spaces of any kind
    )
    (?=             FOLLOWED BY
        \s*,        0 or more empty spaces and a comma
        |           OR
        \s*$        0 or more empty spaces and nothing else (end of string)
    )
    
*/
arr = arr || [];
// this will prevent JS from throwing an error in
// the below loop when there are no matches
for (var i = 0; i < arr.length; i++) console.log('arr['+i+'] =',arr[i]);
于 2012-07-12T18:09:05.903 に答える
10

これを行う JavaScript 関数を次に示します。

function splitCSVButIgnoreCommasInDoublequotes(str) {  
    //split the str first  
    //then merge the elments between two double quotes  
    var delimiter = ',';  
    var quotes = '"';  
    var elements = str.split(delimiter);  
    var newElements = [];  
    for (var i = 0; i < elements.length; ++i) {  
        if (elements[i].indexOf(quotes) >= 0) {//the left double quotes is found  
            var indexOfRightQuotes = -1;  
            var tmp = elements[i];  
            //find the right double quotes  
            for (var j = i + 1; j < elements.length; ++j) {  
                if (elements[j].indexOf(quotes) >= 0) {  
                    indexOfRightQuotes = j; 
                    break;
                }  
            }  
            //found the right double quotes  
            //merge all the elements between double quotes  
            if (-1 != indexOfRightQuotes) {   
                for (var j = i + 1; j <= indexOfRightQuotes; ++j) {  
                    tmp = tmp + delimiter + elements[j];  
                }  
                newElements.push(tmp);  
                i = indexOfRightQuotes;  
            }  
            else { //right double quotes is not found  
                newElements.push(elements[i]);  
            }  
        }  
        else {//no left double quotes is found  
            newElements.push(elements[i]);  
        }  
    }  

    return newElements;  
}  
于 2015-08-12T03:34:06.600 に答える
7

これは私にとってはうまくいきます。(セミコロンを使用したので、配列を文字列に変換するときに追加されたコンマと実際に取得された値の違いがアラート メッセージに表示されます。)

正規表現

/("[^"]*")|[^;]+/

ここに画像の説明を入力

var str = 'a; b; c; "d; e; f"; g; h; "i"';
var array = str.match(/("[^"]*")|[^;]+/g); 
alert(array);
于 2012-07-12T18:48:02.410 に答える
1

少し長いことは承知していますが、私の見解は次のとおりです。

var sample="[a, b, c, \"d, e, f\", g, h]";

var inQuotes = false, items = [], currentItem = '';

for(var i = 0; i < sample.length; i++) {
  if (sample[i] == '"') { 
    inQuotes = !inQuotes; 

    if (!inQuotes) {
      if (currentItem.length) items.push(currentItem);
      currentItem = '';
    }

    continue; 
  }

  if ((/^[\"\[\]\,\s]$/gi).test(sample[i]) && !inQuotes) {
    if (currentItem.length) items.push(currentItem);
    currentItem = '';
    continue;
  }

  currentItem += sample[i];
}

if (currentItem.length) items.push(currentItem);

console.log(items);

補足として、開始と終了に中括弧がある場合とない場合の両方で機能します。

于 2012-07-12T17:42:15.843 に答える
-1

私はこれで同様の問題を抱えていましたが、良い.netソリューションが見つからなかったのでDIYしました。注: これは、への返信にも使用されました。

カンマ区切りの文字列を分割し、引用符内のカンマを無視しますが、1 つの二重引用符を含む文字列を許可します

しかし、ここではより適切なようです(ただし、あちらでは便利です)

私のアプリケーションでは、csv を解析しているので、分割資格情報は "," です。このメソッドは、単一の char split 引数がある場合にのみ機能すると思います。

そこで、二重引用符内のコンマを無視する関数を作成しました。入力文字列を文字配列に変換し、文字を文字ごとに解析することでそれを行います

public static string[] Splitter_IgnoreQuotes(string stringToSplit)
    {   
        char[] CharsOfData = stringToSplit.ToCharArray();
        //enter your expected array size here or alloc.
        string[] dataArray = new string[37];
        int arrayIndex = 0;
        bool DoubleQuotesJustSeen = false;          
        foreach (char theChar in CharsOfData)
        {
            //did we just see double quotes, and no command? dont split then. you could make ',' a variable for your split parameters I'm working with a csv.
            if ((theChar != ',' || DoubleQuotesJustSeen) && theChar != '"')
            {
                dataArray[arrayIndex] = dataArray[arrayIndex] + theChar;
            }
            else if (theChar == '"')
            {
                if (DoubleQuotesJustSeen)
                {
                    DoubleQuotesJustSeen = false;
                }
                else
                {
                    DoubleQuotesJustSeen = true;
                }
            }
            else if (theChar == ',' && !DoubleQuotesJustSeen)
            {
                arrayIndex++;
            }
        }
        return dataArray;
    }

この関数は、私のアプリケーションの好みでは、これらは不要で入力に存在するため、入力の ("") も無視します。

于 2015-05-06T16:04:58.007 に答える
-2

あなたの文字列が実際'[a, b, c, "d, e, f", g, h]'eval()

myString = 'var myArr ' + myString;
eval(myString);

console.log(myArr); // will now be an array of elements: a, b, c, "d, e, f", g, h

編集: Rocket が指摘したように、strictmode は変数をローカル スコープに挿入する機能を削除evalします。つまり、これを行う必要があります。

var myArr = eval(myString);
于 2012-07-12T17:02:28.763 に答える