跳至內容
Astera Technology

拆分標籤時識別經轉義的分隔符

用簡單自訂格式,分清直線字元與清單分隔。

下載完整個案資料及參考答案 ↓

來源格式與預期記錄

這是原創假設轉換例子。輸入限下列欄位的普通、無循環 JSON 形記錄,統一記錄格式及拒絕代碼由本例訂明。若換來源,先修改格式約定。

本例自訂格式以 | 分標籤,反斜線只可轉義 | 或反斜線本身。整段空文字代表沒有標籤;空項、其他轉義及末尾孤立反斜線均拒絕。解碼後保留文字,空格及重複標籤也不刪。

可修改的假設轉換個案
個案輸入記錄(JSON)預期輸出(JSON)
還原字面分隔符{"labels":"fragile\\|blue|heavy"}{"ok":true,"value":{"labels":["fragile|blue","heavy"]}}
拒絕未定轉義{"labels":"a\\q"}{"ok":false,"error":"LABEL_ESCAPE"}
保留空標籤集合{"labels":""}{"ok":true,"value":{"labels":[]}}
下載可編輯 CSV ↓

在本機執行轉換

把完整例子以 JavaScript 模組在 Node.js 執行,內含純轉換函數、三個輸入及寫明的預期輸出,對不上便由斷言停止。拒絕個案回傳 ok=false 及代碼,不回傳半份統一記錄。

完整函數及可執行個案
import assert from 'node:assert/strict';

function escapedLabels(i){
  const fail=error=>({ok:false,error});if(!i||typeof i.labels!=='string')return fail('LABEL_STRING');
  if(i.labels==='')return {ok:true,value:{labels:[]}};
  const labels=[];let value='',escaped=false;
  for(const ch of i.labels){
    if(escaped){if(ch!=='|'&&ch!=='\\')return fail('LABEL_ESCAPE');value+=ch;escaped=false;}
    else if(ch==='\\')escaped=true;
    else if(ch==='|'){if(!value)return fail('EMPTY_LABEL');labels.push(value);value='';}
    else value+=ch;
  }
  if(escaped)return fail('DANGLING_ESCAPE');if(!value)return fail('EMPTY_LABEL');labels.push(value);
  return {ok:true,value:{labels}};
}

// Original synthetic cases; expected outputs are literal records.
const cases = [
  {
    "label": "Decode literal separator",
    "input": {
      "labels": "fragile\\|blue|heavy"
    },
    "expected": {
      "ok": true,
      "value": {
        "labels": [
          "fragile|blue",
          "heavy"
        ]
      }
    }
  },
  {
    "label": "Reject undefined escape",
    "input": {
      "labels": "a\\q"
    },
    "expected": {
      "ok": false,
      "error": "LABEL_ESCAPE"
    }
  },
  {
    "label": "Preserve empty label set",
    "input": {
      "labels": ""
    },
    "expected": {
      "ok": true,
      "value": {
        "labels": []
      }
    }
  }
];
for (const sample of cases) {
  const actual = escapedLabels(sample.input);
  assert.deepEqual(actual, sample.expected);
  console.log(sample.label, JSON.stringify(actual));
}
下載可執行例子 ↓

判清邊界個案

首個案共有多少個標籤?

查看參考答案

兩個:fragile|blue 及 heavy。經轉義的直線留在第一個標籤內,未轉義的才分項;反斜線後接 q 回傳 LABEL_ESCAPE。

相關資源