簡體   English   中英

從字符串正則表達式中提取變量

[英]Extract Variables From String Regex

這可能是一個重復的問題,但我不知道如何尋找答案:P 我正在嘗試從字符串中提取和刪除變量。

該字符串可能如下所示: !text (<123456789>=<@$111111111>) (<7654312> = <@$222222222>) (🛠 =<@$3333333333>) Some text that I will need!

我需要每個塊中的兩個項目? 例如[["123456789", 111111111],['7654312','222222222'],["🛠","3333333333"]]

然后我完全需要字符串但刪除了變量? 例如Some more text that I will need!

我不確定這樣做的最佳方法,任何幫助表示贊賞。

您不必總是使用正則表達式,例如為什么不編寫解析器? 這為您提供了更大的靈活性。 請注意,為了簡單起見,我在🛠周圍添加了<> ,但您可以在解析器中將括號🛠可選。

解析器假定任何不在()都是自由文本並將其捕獲為字符串節點。

例如,如果你只想要最后一個文本節點,你可以做......

const endingText = parse(text).filter(t => typeof t === 'string').pop();

 const text = '!text (<123456789>=<@$111111111>) (<7654312> = <@$222222222>) (<🛠> =<@$3333333333>) Some text that I will need!'; console.log(parse(text)); function parse(input) { let i = 0, char = input[i], text = []; const output = []; while (char) { if (char === '(') { if (text.length) output.push(text.join('')); output.push(entry()); text = []; } else { text.push(char); consume(); } } if (text.length) output.push(text.join('')); return output; function entry() { match('('); const key = value(); whitespace(); match('='); whitespace(); const val = value(); match(')'); return [key, val]; } function value() { const val = []; match('<'); while (char && char !== '>') val.push(char), consume(); match('>'); return val.join(''); } function whitespace() { while (/\\s/.test(char)) consume(); } function consume() { return char = input[++i]; } function match(expected) { if (char !== expected) throw new Error(`Expected '${expected}' at column ${i}.`); consume(); } }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM