You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现函数输入正则校验与数组参数按指定格式字符串格式化输出?

Got it, let's build this function step by step to meet your requirements. Here's a complete implementation that handles input validation and the pattern-based formatting you need:

function doFormat(args, format) {
    // First, validate the input array only contains numbers
    if (!Array.isArray(args) || !args.every(item => typeof item === 'number' && !isNaN(item))) {
        throw new Error('Input must be an array of valid numeric values');
    }

    // Validate the format string only includes plain text and valid \d{...} patterns
    const allowedFormatRegex = /^(\\?[^\\]|\\d\{\d+(,\d+)?\})*$/;
    if (!allowedFormatRegex.test(format)) {
        throw new Error('Format string can only contain regular text and \\d{min,max} or \\d{fixed} patterns');
    }

    // Extract all the digit patterns from the format string
    const digitPatterns = format.match(/\\d\{\d+(,\d+)?\}/g) || [];

    // Make sure we have enough numbers in the array to match all patterns
    if (args.length < digitPatterns.length) {
        throw new Error(`Not enough numeric arguments: expected ${digitPatterns.length}, got ${args.length}`);
    }

    // Process each pattern and replace it with the formatted number
    let resultString = format;
    digitPatterns.forEach((pattern, index) => {
        const number = args[index];
        const numStr = number.toString();
        
        // Extract the length spec from the pattern (e.g., "1,2" from \d{1,2})
        const lengthSpec = pattern.match(/\{(\d+(,\d+)?)\}/)[1];
        let formattedNum;

        if (lengthSpec.includes(',')) {
            // Handle range patterns like \d{1,2}
            const [minLen, maxLen] = lengthSpec.split(',').map(Number);
            // Take up to maxLen digits (truncate from left if needed) and pad to minLen if short
            formattedNum = numStr.slice(0, maxLen).padStart(minLen, '0');
        } else {
            // Handle fixed-length patterns like \d{2}
            const fixedLen = Number(lengthSpec);
            // Pad with leading zeros to reach fixed length, truncate from right if number is too long
            formattedNum = numStr.padStart(fixedLen, '0').slice(-fixedLen);
        }

        // Replace the pattern in the result string
        resultString = resultString.replace(pattern, formattedNum);
    });

    return resultString;
}

// Example usage matching your requirement
const targetFormat = 'Foo \\d{1,2}x\\d{2} Bar';
console.log(doFormat([123, 2, 3], targetFormat)); // Output: "Foo 12x02 Bar"

Breakdown of How It Works

  • Input Validation:

    • Ensures the input args is an array of valid numbers (no strings, NaN, or non-array inputs).
    • Checks that the format string only uses allowed content—no sneaky regex tricks, just plain text and \d{...} patterns.
  • Pattern Matching:

    • Pulls out all the digit patterns from the format string so we know how many numbers we need to format.
    • Throws an error if you don't pass enough numbers to match all the patterns in the format.
  • Number Formatting:

    • For fixed-length patterns like \d{2}: Pads numbers shorter than the length with leading zeros (e.g., 2 → "02") and truncates longer numbers from the right (e.g., 123 → "23").
    • For range patterns like \d{1,2}: Takes up to the maximum number of digits from the start of the number (e.g., 123 → "12") and pads with zeros if the number is shorter than the minimum length (e.g., 5 → "05").
  • Final Replacement:

    • Swaps each \d{...} pattern in the original format string with its corresponding formatted number, keeping all other text intact.

Edge Cases Covered

  • If a number is shorter than the minimum length in a range, it gets padded to meet the minimum.
  • If a number is longer than the maximum length in a range, it gets truncated to fit.
  • Clear error messages help you debug issues with invalid inputs or mismatched argument counts.

内容的提问来源于stack exchange,提问作者Gary

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:15:26