2017-08-26 55 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"));