Напиши скрипт на JS для разбора текстового файла н...

Creato il: 23 marzo 2026

Risposto usando GPT-5.4 Thinking da Chat01

Domanda

Напиши скрипт на JS для разбора текстового файла на файлы функций и процедур /(?:^|\n)(?:[ \t]?//.\n)?(?:(?:[ \t]?&.\n)(?:[ \t]?(?://.)??\n))??[ \t]?(?:Асинх\s?|Async\s*?)??[ \t]?(Процедура|Функция|Procedure|Function)\s(?:[ \t]?(?://.)??\n)[ \t]?([А-Яа-яA-Za-z_][А-Яа-я\w])(?:[ \t]?(?://.)??\n)[ \t]?([\s\S]?\n[ \t]?(?:КонецПроцедуры|КонецФункции|EndProcedure|EndFunction).\n?(?:(?:[ \t]?//.\n)(?=(?:[ \t]?\n)|(?:\s$)))/ig

Pensiero

Creating a Node.js script for splitting files by regex

I’m considering a Node.js script that reads a file, uses the provided regex to split it into separate files by function/procedure name, perhaps with a .bsl or .txt extension. I’ll need to handle missing context, sanitize file names, and be mindful of potential issues with nested constructs in the regex. I'll keep it concise.

Thought for 23s

Risposta

Вот готовый Node.js-скрипт. Он читает текстовый файл, находит все процедуры/функции по твоему regex и раскладывает их в отдельные файлы по имени метода.

js
const fs = require("fs"); const path = require("path"); const INPUT_FILE = process.argv[2]; const OUTPUT_DIR = process.argv[3] || "./out"; if (!INPUT_FILE) { console.error("Использование: node split.js <input-file> [output-dir]"); process.exit(1); } const pattern = /(?:^|\n)(?:[ \t]*?\/\/.*\n)*?(?:(?:[ \t]*?&.*\n)(?:[ \t]*?(?:\/\/.*)??\n)*)??[ \t]*?(?:Асинх\s*?|Async\s*?)??[ \t]*?(Процедура|Функция|Procedure|Function)\s(?:[ \t]*?(?:\/\/.*)??\n)*[ \t]*?([А-Яа-яA-Za-z_][А-Яа-я\w]*)(?:[ \t]*?(?:\/\/.*)??\n)*[ \t]*?\([\s\S]*?\n[ \t]*?(?:КонецПроцедуры|КонецФункции|EndProcedure|EndFunction).*\n?(?:(?:[ \t]*?\/\/.*\n)*(?=(?:[ \t]*?\n)|(?:\s*$)))/ig; function sanitizeFileName(name) { return name.replace(/[<>:"/\\|?*\x00-\x1F]/g, "_"); } function getUniqueFilePath(dir, baseName, ext = ".bsl") { let filePath = path.join(dir, `${baseName}${ext}`); let counter = 1; while (fs.existsSync(filePath)) { filePath = path.join(dir, `${baseName}_${counter}${ext}`); counter++; } return filePath; } function main() { const text = fs.readFileSync(INPUT_FILE, "utf8"); fs.mkdirSync(OUTPUT_DIR, { recursive: true }); let match; let count = 0; while ((match = pattern.exec(text)) !== null) { const fullBlock = match[0].replace(/^\n/, ""); const methodType = match[1]; const methodName = match[2]; const safeName = sanitizeFileName(methodName); const outFile = getUniqueFilePath(OUTPUT_DIR, safeName, ".bsl"); fs.writeFileSync(outFile, fullBlock, "utf8"); count++; console.log(`Сохранено: ${outFile} [${methodType} ${methodName}]`); } console.log(`Готово. Найдено элементов: ${count}`); } main();

Как запускать:

bash
node split.js source.txt ./result

Что делает:

  • читает source.txt
  • ищет все Процедура / Функция / Procedure / Function
  • берёт имя из второй группы regex
  • сохраняет каждый блок в отдельный файл ИмяМетода.bsl

Если хочешь, могу сразу дать версию, которая:

  1. сохраняет процедуры и функции в разные папки,
  2. пишет индексный json,
  3. работает через fs/promises и ES modules.

Condividi questa Q&A