UNPKG

fauton

Version:

A library to test any finite automaton with arbitrary alphabets

98 lines (97 loc) 3.82 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateRegex = void 0; function validateRegex(regexString) { const operations = new Set(['(', '+', '*', '|', '?']); let parenthesisBalance = 0; const literals = new Set(); const noopTokens = [0]; for (let index = 0; index < regexString.length; index += 1) { const regexSymbol = regexString[index]; switch (regexSymbol) { case '(': { parenthesisBalance += 1; noopTokens.push(0); break; } case ')': { parenthesisBalance -= 1; if (parenthesisBalance < 0) { return false; } else if (noopTokens[noopTokens.length - 1] === 0) { return false; } else { noopTokens.pop(); } break; } case '*': case '+': case '?': { if (noopTokens[noopTokens.length - 1] === 0 && literals.size === 0) { return false; } else if (index !== 0 && operations.has(regexString[index - 1])) { return false; } break; } case '|': { if (noopTokens[noopTokens.length - 1] === 0 && literals.size === 0) { return false; } if (noopTokens.length > 1) { let leftRegex = '', rightRegex = '', insideParen = false, lhsParenCount = 0, rhsParenCount = 0; for (let j = 0; j < index; j += 1) { if (regexString[index - j - 1] === ')') { lhsParenCount += 1; } else if (regexString[index - j - 1] === '(') { lhsParenCount -= 1; if (lhsParenCount < 0) { insideParen = true; leftRegex = regexString.slice(index - j, index); break; } } } if (leftRegex === '') { leftRegex = regexString.slice(0, index); rightRegex = regexString.slice(index + 1); } else if (insideParen) { for (let j = index + 1; j < regexString.length; j += 1) { if (regexString[j] === ')') { rhsParenCount -= 1; if (rhsParenCount < 0) { rightRegex = regexString.slice(index + 1, j); } } else if (regexString[j] === '(') { rhsParenCount += 1; } } if (rightRegex === '') { return false; } } if (validateRegex(rightRegex) && validateRegex(leftRegex) === false) { return false; } } break; } default: { literals.add(regexSymbol); noopTokens[noopTokens.length - 1] += 1; } } } if (parenthesisBalance !== 0) { return false; } return true; } exports.validateRegex = validateRegex;