我是 JavaScript 新手,并設法拼湊出一些可行的東西,但我想對其進行改進,以提高效率并便于未來的維護。
該代碼用于辦公腳本,并在 OCR 資料輸出中查找幾個特定的??結構化值,如果找到則回傳值,如果未找到則回傳占位符。這樣就可以在電源自動化中決議輸出陣列。
我只想有一個正則運算式模式陣列來添加或洗掉,結果是一個模式陣列,按陣列的順序排列,如果沒有找到一個值。這樣空值就不會影響我的結果陣列順序。
function main(workbook: ExcelScript.Workbook, inputString: string,): Array<string> {
let GST: Array<string> = inputString.match(RegExp(/(?<![0-9])([0-9]{2,3})[- ]([0-9]{3})[- ]([0-9]{3})(?![0-9])/g));
let NZD: Array<string> = inputString.match(RegExp(/[Nn][Zz][Dd]/g));
let POnum: Array<string> = inputString.match(RegExp(/([aA-zZ]{1,3})-([0-9]{6})-([0-9]{3})(?![0-9])/g));
let BAN: Array<string> = inputString.match(RegExp(/(?<![0-9])([0-9]{2})[- ]([0-9]{4})[- ]([0-9]{7})[- ]([0-9]{2,3})(?![0-9])/g));
if (GST === null) { var Gstvalue = "no match" } else { Gstvalue = GST[0] };
if (NZD === null) { var Nzdvalue = "no match" } else { Nzdvalue = NZD[0] };
if (POnum === null) { var POnumvalue = "no match" } else { POnumvalue = POnum[0] };
if (BAN === null) { var BANvalue = "no match" } else { BANvalue = BAN[0] };
var map = new Map();
map.set('GST',Gstvalue );
map.set('NZD',Nzdvalue);
map.set('POnum', POnumvalue);
map.set('BAN', BANvalue);
return [map.get('GST'), map.get('NZD'), map.get('POnum'), map.get('BAN')]
}
uj5u.com熱心網友回復:
您的代碼可以大大簡化為一組正則運算式并對其進行映射:
function main(workbook: ExcelScript.Workbook, inputString: string): Array<string> {
const regex = [
/(?<![0-9])([0-9]{2,3})[- ]([0-9]{3})[- ]([0-9]{3})(?![0-9])/g,
/[Nn][Zz][Dd]/g,
/([aA-zZ]{1,3})-([0-9]{6})-([0-9]{3})(?![0-9])/g,
/(?<![0-9])([0-9]{2})[- ]([0-9]{4})[- ]([0-9]{7})[- ]([0-9]{2,3})(?![0-9])/g,
];
// for each pattern we have
return regex.map((re) => {
// matches for this particular regex
const match = inputString.match(re);
// no match
if (match === null) return "no match";
// first match
return match[0];
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/528987.html
