JavaScript Python PHP
function executar(values) {
// RegExp JavaScript: execute esta função em um Worker cancelável em 2s ao aceitar entradas não confiáveis.
function lgText(value) { if (typeof value !== 'string' || value.length > 100000 || !value.isWellFormed())
throw new Error('Use texto Unicode válido de até 100 mil caracteres por campo.'); return value; }
function testLogicRegex(v) {
const mode = lgChoice(v, 'mode', ['Expressão', 'Literal', 'Inteiro', 'Palavra']), flags = v.flags;
if (!/^[gimsu]*$/.test(flags) || new Set(flags).size !== flags.length)
throw new Error('Flags aceitas: g, i, m, s, u, sem repetição.');
if (v.pattern.length > 1000 || v.replacement.length > 1000 || v.input.length > 10000)
throw new Error('Limites: padrão/substituição 1.000 caracteres; texto 10 mil.');
const pattern = mode === 'Literal' ? v.pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') : mode === 'Inteiro' ? '-?\\d+' : mode === 'Palavra' ? '\\p{L}+' : v.pattern;
const actualFlags = mode === 'Palavra' && !flags.includes('u') ? flags + 'u' : flags;
let expression;
try {
expression = new RegExp(pattern, actualFlags + 'd');
}
catch (cause) {
throw new Error('Expressão regular inválida: ' + (cause instanceof Error ? cause.message : 'confira o padrão.'));
}
const matches = [];
let match;
while ((match = expression.exec(v.input)) !== null) {
if (matches.length >= 500)
throw new Error('Mais de 500 correspondências. Reduza o texto ou restrinja o padrão.');
matches.push({ text: match[0], start: match.index, end: match.index + match[0].length, groups: match.slice(1).map(x => x ?? null), named: Object.fromEntries(Object.entries(match.groups ?? {}).map(([key, value]) => [key, value ?? null])), ranges: Array.from(match.indices ?? [], range => range ?? null) });
if (!actualFlags.includes('g'))
break;
if (match[0] === '')
expression.lastIndex += actualFlags.includes('u') && (v.input.codePointAt(expression.lastIndex) ?? 0) > 65535 ? 2 : 1;
}
const replaced = v.input.replace(new RegExp(pattern, actualFlags), v.replacement);
return { ...lgJson({ pattern, flags: actualFlags, count: matches.length, matches, replaced }), matches, input: v.input };
}
function lgChoice(v, key, choices) { if (!choices.includes(v[key]))
throw new Error(`Opção inválida: ${key}.`); return v[key]; }
function lgJson(value, compact = false) { const text = JSON.stringify(value, null, compact ? undefined : 2); if (text.length > 1000000)
throw new Error('Resultado excede 1 milhão de caracteres. Reduza os limites.'); return { text, file: 'resultado.json' }; }
for (const value of Object.values(values)) lgText(value);
return testLogicRegex(values);
}
import json
import subprocess
def executar(values):
# Dialeto RegExp de JavaScript: requer Node.js 22+. Lógica completa abaixo, sem módulos do projeto.
source = r'''
function executar(values) {
// RegExp JavaScript: execute esta função em um Worker cancelável em 2s ao aceitar entradas não confiáveis.
function lgText(value) { if (typeof value !== 'string' || value.length > 100000 || !value.isWellFormed())
throw new Error('Use texto Unicode válido de até 100 mil caracteres por campo.'); return value; }
function testLogicRegex(v) {
const mode = lgChoice(v, 'mode', ['Expressão', 'Literal', 'Inteiro', 'Palavra']), flags = v.flags;
if (!/^[gimsu]*$/.test(flags) || new Set(flags).size !== flags.length)
throw new Error('Flags aceitas: g, i, m, s, u, sem repetição.');
if (v.pattern.length > 1000 || v.replacement.length > 1000 || v.input.length > 10000)
throw new Error('Limites: padrão/substituição 1.000 caracteres; texto 10 mil.');
const pattern = mode === 'Literal' ? v.pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') : mode === 'Inteiro' ? '-?\\d+' : mode === 'Palavra' ? '\\p{L}+' : v.pattern;
const actualFlags = mode === 'Palavra' && !flags.includes('u') ? flags + 'u' : flags;
let expression;
try {
expression = new RegExp(pattern, actualFlags + 'd');
}
catch (cause) {
throw new Error('Expressão regular inválida: ' + (cause instanceof Error ? cause.message : 'confira o padrão.'));
}
const matches = [];
let match;
while ((match = expression.exec(v.input)) !== null) {
if (matches.length >= 500)
throw new Error('Mais de 500 correspondências. Reduza o texto ou restrinja o padrão.');
matches.push({ text: match[0], start: match.index, end: match.index + match[0].length, groups: match.slice(1).map(x => x ?? null), named: Object.fromEntries(Object.entries(match.groups ?? {}).map(([key, value]) => [key, value ?? null])), ranges: Array.from(match.indices ?? [], range => range ?? null) });
if (!actualFlags.includes('g'))
break;
if (match[0] === '')
expression.lastIndex += actualFlags.includes('u') && (v.input.codePointAt(expression.lastIndex) ?? 0) > 65535 ? 2 : 1;
}
const replaced = v.input.replace(new RegExp(pattern, actualFlags), v.replacement);
return { ...lgJson({ pattern, flags: actualFlags, count: matches.length, matches, replaced }), matches, input: v.input };
}
function lgChoice(v, key, choices) { if (!choices.includes(v[key]))
throw new Error(`Opção inválida: ${key}.`); return v[key]; }
function lgJson(value, compact = false) { const text = JSON.stringify(value, null, compact ? undefined : 2); if (text.length > 1000000)
throw new Error('Resultado excede 1 milhão de caracteres. Reduza os limites.'); return { text, file: 'resultado.json' }; }
for (const value of Object.values(values)) lgText(value);
return testLogicRegex(values);
}
let input=""; for await (const chunk of process.stdin) input+=chunk; try { process.stdout.write(JSON.stringify({ok:true,result:executar(JSON.parse(input))})); } catch (error) { process.stdout.write(JSON.stringify({ok:false,error:error.message})); }
'''
try:
process = subprocess.run(["node", "--input-type=module", "-e", source], input=json.dumps(values, ensure_ascii=True), capture_output=True, text=True, timeout=2, check=True)
except subprocess.TimeoutExpired as error:
raise ValueError("Processamento interrompido após 2 segundos.") from error
response = json.loads(process.stdout)
if not response["ok"]:
raise ValueError(response["error"])
return response["result"]
<?php
function executar(array $values): array {
// Dialeto RegExp de JavaScript: requer Node.js 22+. Lógica completa abaixo, sem módulos do projeto.
$source = <<<'JAVASCRIPT'
function executar(values) {
// RegExp JavaScript: execute esta função em um Worker cancelável em 2s ao aceitar entradas não confiáveis.
function lgText(value) { if (typeof value !== 'string' || value.length > 100000 || !value.isWellFormed())
throw new Error('Use texto Unicode válido de até 100 mil caracteres por campo.'); return value; }
function testLogicRegex(v) {
const mode = lgChoice(v, 'mode', ['Expressão', 'Literal', 'Inteiro', 'Palavra']), flags = v.flags;
if (!/^[gimsu]*$/.test(flags) || new Set(flags).size !== flags.length)
throw new Error('Flags aceitas: g, i, m, s, u, sem repetição.');
if (v.pattern.length > 1000 || v.replacement.length > 1000 || v.input.length > 10000)
throw new Error('Limites: padrão/substituição 1.000 caracteres; texto 10 mil.');
const pattern = mode === 'Literal' ? v.pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') : mode === 'Inteiro' ? '-?\\d+' : mode === 'Palavra' ? '\\p{L}+' : v.pattern;
const actualFlags = mode === 'Palavra' && !flags.includes('u') ? flags + 'u' : flags;
let expression;
try {
expression = new RegExp(pattern, actualFlags + 'd');
}
catch (cause) {
throw new Error('Expressão regular inválida: ' + (cause instanceof Error ? cause.message : 'confira o padrão.'));
}
const matches = [];
let match;
while ((match = expression.exec(v.input)) !== null) {
if (matches.length >= 500)
throw new Error('Mais de 500 correspondências. Reduza o texto ou restrinja o padrão.');
matches.push({ text: match[0], start: match.index, end: match.index + match[0].length, groups: match.slice(1).map(x => x ?? null), named: Object.fromEntries(Object.entries(match.groups ?? {}).map(([key, value]) => [key, value ?? null])), ranges: Array.from(match.indices ?? [], range => range ?? null) });
if (!actualFlags.includes('g'))
break;
if (match[0] === '')
expression.lastIndex += actualFlags.includes('u') && (v.input.codePointAt(expression.lastIndex) ?? 0) > 65535 ? 2 : 1;
}
const replaced = v.input.replace(new RegExp(pattern, actualFlags), v.replacement);
return { ...lgJson({ pattern, flags: actualFlags, count: matches.length, matches, replaced }), matches, input: v.input };
}
function lgChoice(v, key, choices) { if (!choices.includes(v[key]))
throw new Error(`Opção inválida: ${key}.`); return v[key]; }
function lgJson(value, compact = false) { const text = JSON.stringify(value, null, compact ? undefined : 2); if (text.length > 1000000)
throw new Error('Resultado excede 1 milhão de caracteres. Reduza os limites.'); return { text, file: 'resultado.json' }; }
for (const value of Object.values(values)) lgText(value);
return testLogicRegex(values);
}
let input=""; for await (const chunk of process.stdin) input+=chunk; try { process.stdout.write(JSON.stringify({ok:true,result:executar(JSON.parse(input))})); } catch (error) { process.stdout.write(JSON.stringify({ok:false,error:error.message})); }
JAVASCRIPT;
$process = proc_open(["node", "--input-type=module", "-e", $source], [["pipe", "r"], ["pipe", "w"], ["pipe", "w"]], $pipes);
if (!is_resource($process)) throw new RuntimeException("Não foi possível iniciar Node.js.");
$payload = json_encode($values, JSON_THROW_ON_ERROR);
$offset = 0;
while ($offset < strlen($payload)) { $written = fwrite($pipes[0], substr($payload, $offset)); if ($written === false || $written === 0) { proc_terminate($process); foreach ($pipes as $pipe) fclose($pipe); proc_close($process); throw new RuntimeException("Falha ao enviar entrada."); } $offset += $written; }
fclose($pipes[0]);
stream_set_blocking($pipes[1], false); stream_set_blocking($pipes[2], false);
$deadline = hrtime(true) + 2000000000; $output = ""; $errors = ""; $timeout = false; $exit = -1;
while (true) {
$output .= stream_get_contents($pipes[1]); $errors .= stream_get_contents($pipes[2]);
$status = proc_get_status($process);
if (!$status["running"]) { $exit = $status["exitcode"]; break; }
if (hrtime(true) >= $deadline) { $timeout = true; proc_terminate($process, 9); break; }
usleep(10000);
}
$output .= stream_get_contents($pipes[1]); fclose($pipes[1]); fclose($pipes[2]); proc_close($process);
if ($timeout) throw new InvalidArgumentException("Processamento interrompido após 2 segundos.");
if ($exit !== 0) throw new RuntimeException("Falha técnica no Node.js.");
$response = json_decode($output, false, 512, JSON_THROW_ON_ERROR);
if (!$response->ok) throw new InvalidArgumentException($response->error);
return (array)$response->result;
}