2017-08-26 186 views
0

我知道如何使用util.format()使用%f,%d等格式化字符串。有人可以告诉我哪个是可以从字符串扫描(而不是从控制台输入)启用的补充功能。Node.js中util.format()的补充函数

例如:

运行...

const util = require('util'); 
var weatherStr = util.format(`The temperature at %d o' clock was %f deg. C and the humidity was %f.`, 5, 23.9, 0.5); 
console.log(weatherStr); 

... ...产生

The temperature at 5 o' clock was 23.9 deg. C and the humidity was 0.5. 

我期待一个实用程序函数,它会工作,使得运行以下代码...

const util = require('util'); 
var weatherStr = 'The temperature at 5 o' clock was 23.9 deg. C and the humidity was 0.5.'; 
console.log(util.????(tempStr, `humidity was %f.`)); 

...生成...

0.5 

这是一个util函数吗?我不认为“parseFloat”会起作用,因为它会提取23.9。

我是新来的JS和节点,但我希望有一个“扫描”功能。我知道有一个scanf npm库,但它似乎与控制台输入,而不是现有的字符串。我一直在搜索JS和Node函数中的“%f”,并且令人惊讶的是util.format似乎是唯一一个提及它的。

回答

0

感谢trincot!

事实上,它变成scanf npm库(https://www.npmjs.com/package/scanf)能解决我的问题。我只是没有读完。我不得不安装“sscanf”(注意double-s)。 sscanf方法(列在包页面的底部)按照我的预期工作。

我很惊讶这个包没有更受欢迎,但它是我所需要的。再次感谢!

1

我不知道这样的扫描库,但你可以使用正则表达式。这里有一些模式,你可以使用:

  • 整数:[+-]?\d+
  • 十进制:[+-]?\d+(?:\.\d+)?

如果你在一个捕获组把这些,你可以从阵列访问相应的匹配是String#match回报:

var weatherStr = "The temperature at 5 o'clock was 23.9 deg. C and the humidity was 0.5."; 
 
console.log(+weatherStr.match(/humidity was ([+-]?\d+(?:\.\d+)?)./)[1]);

您可以创建一个实用功能,可以处理%d%f

function scanf(input, find) { 
 
    var pattern = { 
 
     "d": "(\\d+)", 
 
     "f": "(\\d+(?:\\.\\d+)?)" 
 
    }; 
 
    find = find 
 
     // Escape characters for use in RegExp constructor: 
 
     .replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') 
 
     // Replace %-patterns 
 
     .replace(/((?:\\)*)%([a-z])/g, function (m, a, b) { 
 
      return a.length % 4 == 0 && b in pattern ? a + pattern[b] : m; 
 
     }); 
 
    var match = input.match(new RegExp(find)); 
 
    return match && match.slice(1).map(Number); 
 
} 
 

 
var weatherStr = "The temperature at 5 o'clock was 23.9 deg. C and the humidity was 0.5."; 
 
console.log(scanf(weatherStr, "humidity was %f")); 
 
console.log(scanf(weatherStr, "at %d o'clock was %f"));