Nodejs 相当于 c sscanf

问题描述

我需要一个行为类似于 sscanf

行为的函数

例如,假设我们有一个看起来像这样的格式字符串(我正在寻找的函数不必完全像这样,而是类似的)

"This is normal text that has to exactly match,but here is a ${var}"

并返回/修改一个变量看起来像

{'var': <whatever was there>}

在研究了一段时间后,我真正能找到的唯一东西是 scanf,但这需要输入表单 stdin,而不是 string

我知道有一个正则表达式解决方案,但我正在寻找一个不需要正则表达式的函数(正则表达式很慢)。但是,如果没有其他解决方案,我将接受正则表达式解决方案。

解决方法

您的意思是让 ${var} 充当占位符吗?如果是这样,您可以通过用反引号替换 " 来实现:

console.log(`This is normal text that has to exactly match,but here is a ${"whatever was there"}`)