简体   繁体   English

从字符串正则表达式中提取变量

[英]Extract Variables From String Regex

This might be a repeat question but I'm not sure how to look for the answer :P I'm trying to extract and remove variables from a string.这可能是一个重复的问题,但我不知道如何寻找答案:P 我正在尝试从字符串中提取和删除变量。

The string might look like this: !text (<123456789>=<@$111111111>) (<7654312> = <@$222222222>) (🛠 =<@$3333333333>) Some text that I will need!该字符串可能如下所示: !text (<123456789>=<@$111111111>) (<7654312> = <@$222222222>) (🛠 =<@$3333333333>) Some text that I will need!

I need the two items in each block?我需要每个块中的两个项目? eg [["123456789", 111111111],['7654312','222222222'],["🛠","3333333333"]]例如[["123456789", 111111111],['7654312','222222222'],["🛠","3333333333"]]

Then I need the string exactly but with the variables removed?然后我完全需要字符串但删除了变量? eg Some more text that I will need!例如Some more text that I will need!

I'm not sure of the best way to do this, any help is appreciated.我不确定这样做的最佳方法,任何帮助表示赞赏。

You don't always have to use regexes, for instance why not write a parser?您不必总是使用正则表达式,例如为什么不编写解析器? This gives you much more flexibility.这为您提供了更大的灵活性。 Note that I added <> around the 🛠 for simplicity, but you could make brackets optional in the parser.请注意,为了简单起见,我在🛠周围添加了<> ,但您可以在解析器中将括号🛠可选。

The parser assumes anything that isin't within () is free text and captures it as string nodes.解析器假定任何不在()都是自由文本并将其捕获为字符串节点。

For instance if you wanted only the last text node you could do...例如,如果你只想要最后一个文本节点,你可以做......

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