[英]How to get a number at the end of a string followed by this character `:` using regex
[英]How to split string followed by number and units in array by regex
我有這樣的數組,只有幾個值:名稱、數字(int 或 float)和 %。 這是它的外觀:
["Ingredients", " Corn starch 33.02%", " sugar 22.21%", " sea salt 20.27% [1]", " peas 10%"]
現在在幾個步驟中我需要刪除 [*] 所以我有這部分:
for (var i = 1; i < lines .length; i++) {
array1.push(lines [i].replace(/\[.*?\]/g, ''));
現在我完成的部分不知道如何將它們分成3個值,我對第一個值的預期 output 是:
1 : corn starch , 33.02 , %
你能幫我找到正則表達式來拆分它嗎?
我做了以下:
const lines = ["Ingredients", " Corn starch 33.02%", " sugar 22.21%", " sea salt 20.27% [1]", " peas 10%"]; const results = []; lines.forEach(line => { const filtered = line.split(/([\s\w]+)\s(\d+(?:\.\d+)?)(%?)\s?(?:\[\d\])?/g).filter(Boolean); results.push(filtered); }); console.log(results)
我不是正則表達式專家,所以肯定會有我錯過的東西,但這似乎適用於給定的輸入。 你可以在這里玩它: regexr
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.