如何通过条件正则替换添加连字符实现Web API字符串格式化?
Got it, let's tackle this problem step by step—we need to handle two core tasks: building regex-based logic to insert hyphens per your prefix/length rules, and creating a web API that uses this formatting logic. Since this is a pass-through system, we don’t need to validate the actual character content—we just focus on structuring the string correctly.
Your rule set depends on the first two characters and total string length, plus an optional third hyphen. A pure regex approach can work for specific cases, but combining regex with a configurable function is way more maintainable for multiple rule combinations.
First, let’s use a rule configuration object to map prefix-length pairs to grouping patterns (easy to expand later):
// Configurable rule set: key = "prefix-totalLength", value = group lengths after prefix const formattingRules = { "AB-10": { groups: [4, 3, 1] }, // Example: AB + 8 chars → AB-XXXX-XXX-X "XY-8": { groups: [3, 2, 1] }, // Example: XY + 6 chars → XY-XXX-XX-X "CD-12": { groups: [5, 3, 2] } // Add more rules here as needed }; function formatString(input) { if (!input || typeof input !== "string") { return { error: "Invalid input: must be a non-empty string" }; } const prefix = input.slice(0, 2); const totalLength = input.length; const ruleKey = `${prefix}-${totalLength}`; const rule = formattingRules[ruleKey]; if (!rule) { return { original: input, formatted: "No matching formatting rule found" }; } const rest = input.slice(2); let withThirdHyphen = prefix; let currentIndex = 0; // Build the formatted string with the third hyphen for (const groupLen of rule.groups) { const group = rest.slice(currentIndex, currentIndex + groupLen); withThirdHyphen += `-${group}`; currentIndex += groupLen; } // Build the alternative without the third hyphen (merge last two groups) const [firstGroupLen, ...remainingGroups] = rule.groups; const mergedLastGroups = rest.slice(firstGroupLen); const withoutThirdHyphen = `${prefix}-${rest.slice(0, firstGroupLen)}-${mergedLastGroups}`; return { original: input, formatted: { withThirdHyphen, withoutThirdHyphen } }; }
If you need a pure regex for a specific rule (e.g., AB prefix, length 10), here’s how that looks:
// Matches AB followed by 8 characters, split into 4+3+1 or 4+4 ^(AB)(.{4})(.{3})(.{1})$|^(AB)(.{4})(.{4})$
- Replace with
$1-$2-$3-$4for the version with the third hyphen - Replace with
$5-$6-$7for the version without it
Let’s build a lightweight API using Node.js + Express (super common for this use case). First, install dependencies:
npm install express
Then write the API code:
const express = require("express"); const app = express(); app.use(express.json()); // Paste the formattingRules object and formatString function here // API endpoint to handle string formatting app.post("/format-string", (req, res) => { const { input } = req.body; const result = formatString(input); res.status(result.error ? 400 : 200).json(result); }); // Start the server const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`API running on http://localhost:${PORT}`); });
Python/Flask Alternative
If you prefer Python, here’s the equivalent API:
from flask import Flask, request, jsonify app = Flask(__name__) formatting_rules = { "AB-10": {"groups": [4, 3, 1]}, "XY-8": {"groups": [3, 2, 1]} } def format_string(input_str): if not isinstance(input_str, str) or len(input_str) < 2: return {"error": "Invalid input: must be a string with at least 2 characters"} prefix = input_str[:2] total_length = len(input_str) rule_key = f"{prefix}-{total_length}" rule = formatting_rules.get(rule_key) if not rule: return {"original": input_str, "formatted": "No matching formatting rule found"} rest = input_str[2:] with_third_hyphen = prefix current_index = 0 for group_len in rule["groups"]: group = rest[current_index:current_index + group_len] with_third_hyphen += f"-{group}" current_index += group_len first_group_len = rule["groups"][0] merged_last_groups = rest[first_group_len:] without_third_hyphen = f"{prefix}-{rest[:first_group_len]}-{merged_last_groups}" return { "original": input_str, "formatted": { "withThirdHyphen": with_third_hyphen, "withoutThirdHyphen": without_third_hyphen } } @app.route("/format-string", methods=["POST"]) def format_string_api(): data = request.get_json() input_str = data.get("input") result = format_string(input_str) status_code = 400 if "error" in result else 200 return jsonify(result), status_code if __name__ == "__main__": app.run(port=3000, debug=True)
- The rule configuration makes it trivial to add new prefix-length combinations later—no need to rewrite core logic.
- Since this is a pass-through system, we skip character validation (e.g., checking if segments are numbers). Add that if you need it later.
- The API returns both formatted variants (with/without the third hyphen) by default. You can modify it to accept a query parameter (like
?includeThirdHyphen=true) to let clients choose.
内容的提问来源于stack exchange,提问作者Seth

