[英]Complementary function to util.format() in Node.js
我知道如何使用util.format()使用%f,%d等格式化字符串。 有人可以告訴我,哪個是補充功能,可以從字符串(而不是從控制台輸入)啟用掃描。
例如:
正在運行...
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.
我期待一個util函數可以正常運行,以便運行以下代碼...
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和Node的新手,但我希望使用“掃描”功能。 我知道有一個scanf npm庫,但它似乎可以在控制台輸入而不是現有的字符串下工作。 我一直在JS和Node函數中搜索“%f”,令人驚訝的是util.format似乎是唯一提及它的人。
我不知道像這樣的任何掃描庫,但是您可以使用正則表達式。 這是您可以使用的一些模式:
[+-]?\\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(/((?:\\\\)*)%([az])/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"));
謝謝小裝飾品!
實際上,事實證明scanf npm庫( https://www.npmjs.com/package/scanf )確實解決了我的問題。 我只是沒有完全閱讀它。 我還必須安裝“ sscanf”(注意double -s)。 sscanf方法(在軟件包頁面的底部列出)可以正常工作。
令我感到驚訝的是,這種包裝沒有受歡迎,但這正是我所需要的。 再次感謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.