rgex
Version:
A powerful, chainable regex builder platform with comprehensive validation utilities
399 lines • 20.1 kB
TypeScript
/**
* RGex Human Text Parser
* Converts human-readable text descriptions to regex patterns
*/
import type { TextExtractionResult, ValidationExtractionResult } from '../../types/index.js';
/**
* Parses a human-readable string to generate a regular expression.
* It first attempts to find complex, compound patterns, then looks for direct keyword matches,
* and finally falls back to constructing a pattern from individual text components.
*
* @param humanText - The natural language string describing the desired regex.
* @param testValue - An optional string to test against the generated regex for confidence scoring.
* @returns A `TextExtractionResult` object containing the generated pattern, confidence, and other metadata.
*/
export declare function parseHumanTextToRegex(humanText: string, testValue?: string): TextExtractionResult;
/**
* Parses a human-readable string to extract a set of validation rules.
* It identifies keywords for common validation requirements (e.g., "required", "strong password")
* and also leverages `parseHumanTextToRegex` to create pattern-based rules.
*
* @param humanText - The natural language string describing the validation requirements.
* @param testValue - An optional string to test the extracted rules against.
* @returns A `ValidationExtractionResult` object containing the rules, confidence, and other metadata.
*/
export declare function parseHumanTextToValidation(humanText: string, testValue?: string): ValidationExtractionResult;
/**
* Provides regex pattern suggestions based on keywords found in the input text.
* @param text - The user-provided text to analyze for suggestions.
* @returns An array of string suggestions, limited to the top 5 most relevant.
*/
export declare function getPatternSuggestions(text: string): string[];
/**
* Converts human-readable text descriptions into regular expression patterns.
* This is a convenient alias for `parseHumanTextToRegex` that provides the same functionality
* with natural language processing to understand pattern requirements.
*
* @param humanText - Natural language description of the desired regex pattern.
* Examples: "email address", "phone number with dashes", "text that starts with A"
* @param testValue - Optional test string to validate the generated pattern against
* and improve confidence scoring. If provided, the function will test the pattern
* and adjust confidence based on whether the test passes.
* @returns A `TextExtractionResult` object containing:
* - `success`: Boolean indicating if pattern generation succeeded
* - `pattern`: Generated RegExp object (undefined if failed)
* - `confidence`: Number between 0-1 indicating pattern reliability
* - `description`: Human-readable description of the generated pattern
* - `suggestions`: Array of helpful suggestions for improvement
*
* @example
* ```typescript
* // Basic email pattern
* const result = humanToRegex("email address");
* console.log(result.pattern); // /^[^\s@]+@[^\s@]+\.[^\s@]+$/
*
* // Complex positional pattern
* const startPattern = humanToRegex("starts with 'user_' followed by numbers");
*
* // With test validation
* const phoneResult = humanToRegex("US phone number", "+1-555-123-4567");
* console.log(phoneResult.confidence); // Higher confidence due to successful test
* ```
*/
export declare const humanToRegex: typeof parseHumanTextToRegex;
/**
* Transforms textual pattern descriptions into executable regular expressions.
* This is an intuitive alias for `parseHumanTextToRegex` that emphasizes text-to-regex
* conversion capability, supporting complex multi-part requirements and natural language.
*
* @param humanText - Descriptive text explaining the pattern requirements.
* Supports complex descriptions like: "alphanumeric with dashes between 5 and 50 characters",
* "email that contains numbers in domain", "text starting with capital and ending with period"
* @param testValue - Optional validation string to test pattern accuracy and boost confidence.
* When provided, the generated regex is tested against this value to ensure correctness.
* @returns Complete `TextExtractionResult` with pattern, confidence metrics, and guidance:
* - `success`: Whether the text was successfully parsed into a pattern
* - `pattern`: The generated RegExp ready for use (null if parsing failed)
* - `confidence`: Reliability score from 0.0 (low) to 1.0 (high confidence)
* - `description`: Clear explanation of what the pattern matches
* - `suggestions`: Actionable advice for improving pattern or handling edge cases
*
* @example
* ```typescript
* // Simple pattern conversion
* const digits = textToRegex("exactly 5 digits");
* // Result: /^\d{5}$/
*
* // Complex compound pattern
* const complex = textToRegex("username that starts with letter, contains numbers, and is 3-20 characters");
*
* // Financial pattern with validation
* const creditCard = textToRegex("credit card number", "4532-1234-5678-9012");
* if (creditCard.success) {
* console.log(`Pattern confidence: ${creditCard.confidence}`);
* }
* ```
*/
export declare const textToRegex: typeof parseHumanTextToRegex;
/**
* Extracts validation rules from human-readable requirement descriptions.
* This alias for `parseHumanTextToValidation` converts natural language validation
* requirements into structured validation rule objects with patterns and functions.
*
* @param humanText - Natural language describing validation requirements.
* Examples: "required email", "strong password with special characters",
* "optional phone number", "text between 10 and 100 characters"
* @param testValue - Optional input to validate against the extracted rules.
* Helps determine rule accuracy and provides immediate feedback on compliance.
* @returns Comprehensive `ValidationExtractionResult` containing:
* - `success`: Boolean indicating successful rule extraction
* - `rules`: Array of `ValidationRule` objects with patterns, validators, and messages
* - `confidence`: Overall confidence in the extracted validation logic
* - `description`: Summary of extracted validation requirements
* - `suggestions`: Helpful tips for improving validation or fixing issues
* - `allPassed`: Boolean indicating if test value passes all rules (when provided)
* - `caseUnPassed`: Array of rule names that failed validation (when test provided)
*
* @example
* ```typescript
* // Basic required field
* const emailValidation = humanToValidation("required email address");
* // Returns rules for: required field + email format
*
* // Complex password requirements
* const passwordRules = humanToValidation("strong password minimum 8 characters");
*
* // With immediate testing
* const result = humanToValidation("required phone number", "555-1234");
* console.log(result.allPassed); // true/false
* console.log(result.caseUnPassed); // ["required", "phoneFormat"] if failed
* ```
*/
export declare const humanToValidation: typeof parseHumanTextToValidation;
/**
* Converts descriptive text into structured validation rule sets.
* This practical alias for `parseHumanTextToValidation` specializes in transforming
* textual validation requirements into actionable validation logic with error messages.
*
* @param humanText - Textual description of validation needs and constraints.
* Supports complex scenarios: "mandatory email with custom domain",
* "secure password with mixed case and symbols", "conditional phone number format"
* @param testValue - Optional sample input for immediate rule testing and validation.
* Provides real-time feedback on whether the input meets the described requirements.
* @returns Detailed `ValidationExtractionResult` with comprehensive validation data:
* - `success`: Indicates whether meaningful validation rules were extracted
* - `rules`: Structured array of validation rules with patterns and custom validators
* - `confidence`: Numeric confidence score reflecting extraction accuracy
* - `description`: Human-friendly summary of the validation requirements
* - `suggestions`: Constructive guidance for improving validation or input format
* - `allPassed`: Overall validation status when test value is provided
* - `caseUnPassed`: Specific validation rules that failed (helps with debugging)
*
* @example
* ```typescript
* // Form field validation
* const usernameRules = textToValidation("required username 3-20 characters alphanumeric only");
*
* // Multi-constraint validation
* const complexRules = textToValidation("password minimum 12 characters with uppercase lowercase numbers symbols");
*
* // Real-time validation feedback
* const validation = textToValidation("required credit card", "4532-1234-5678-9012");
* validation.rules.forEach(rule => {
* if (rule.pattern && !rule.pattern.test("4532-1234-5678-9012")) {
* console.log(`Failed: ${rule.message}`);
* }
* });
* ```
*/
export declare const textToValidation: typeof parseHumanTextToValidation;
/**
* Provides intelligent pattern suggestions based on partial or unclear text input.
* This helpful alias for `getPatternSuggestions` analyzes user input and offers
* relevant pattern recommendations, keywords, and examples to guide pattern creation.
*
* @param text - Partial or unclear text input that needs pattern suggestions.
* Can be incomplete words, typos, or vague descriptions that need clarification.
* Examples: "emai", "phon numb", "date tim", "secur password"
* @returns Array of helpful suggestion strings (limited to top 5 most relevant):
* - Pattern keyword suggestions based on partial matches
* - Available pattern types and their trigger keywords
* - Example phrases that work well with the parser
* - General guidance for improving pattern descriptions
*
* @example
* ```typescript
* // Get suggestions for partial input
* const suggestions = getSuggestions("emai");
* // Returns: ["Did you mean 'email'? Try: email, email address, e-mail"]
*
* // Help with unclear input
* const phoneHelp = getSuggestions("phone");
* // Returns suggestions for phone patterns, formats, and examples
*
* // General pattern guidance
* const general = getSuggestions("xyz123");
* // Returns: ["Available patterns: email, phone, url, date...", "Use descriptive keywords..."]
* ```
*/
export declare const getSuggestions: typeof getPatternSuggestions;
/**
* Generates contextual pattern suggestions from text analysis.
* This intelligent alias for `getPatternSuggestions` analyzes input text and provides
* smart recommendations for pattern creation, helping users discover available patterns
* and improve their natural language descriptions.
*
* @param text - Input text to analyze for pattern suggestion opportunities.
* Accepts typos, partial words, unclear descriptions, or exploratory queries.
* The function intelligently matches against known pattern keywords and provides guidance.
* @returns Curated array of suggestion strings (maximum 5) including:
* - Corrections for misspelled pattern keywords
* - Lists of available pattern types with trigger words
* - Example phrases that demonstrate proper usage
* - Best practices for writing clear pattern descriptions
*
* @example
* ```typescript
* // Typo correction
* const corrections = textToSuggestions("emial addres");
* // Returns suggestions to use "email address"
*
* // Pattern discovery
* const discovery = textToSuggestions("number");
* // Returns various number patterns: phone, credit card, zip code, etc.
*
* // Blank slate guidance
* const help = textToSuggestions("");
* // Returns: ["Available patterns: email, phone, url...", "Use descriptive keywords..."]
* ```
*/
export declare const textToSuggestions: typeof getPatternSuggestions;
/**
* Quick human-to-regex conversion with abbreviated syntax.
* This compact alias for `parseHumanTextToRegex` provides the same powerful
* natural language processing in a shortened form ideal for rapid development
* and inline pattern generation.
*
* @param humanText - Concise natural language pattern description.
* Same capabilities as the full function: complex patterns, compound requirements,
* positional constraints, and specialized domain patterns (email, phone, etc.)
* @param testValue - Optional validation string for confidence boosting and accuracy testing.
* When provided, tests the generated pattern and adjusts confidence accordingly.
* @returns Standard `TextExtractionResult` with full pattern generation results:
* - `success`: Pattern generation success indicator
* - `pattern`: Generated RegExp object for immediate use
* - `confidence`: Reliability score from 0.0 to 1.0
* - `description`: Clear explanation of pattern behavior
* - `suggestions`: Improvement recommendations and usage tips
*
* @example
* ```typescript
* // Quick email pattern
* const email = h2r("email");
*
* // Rapid validation setup
* const phone = h2r("US phone", "+1-555-0123");
* if (phone.success && phone.confidence > 0.8) {
* // Use phone.pattern for validation
* }
*
* // Inline pattern generation
* const isValid = h2r("starts with A ends with Z").pattern?.test("AMAZING");
* ```
*/
export declare const h2r: typeof parseHumanTextToRegex;
/**
* Efficient text-to-regex transformation with streamlined syntax.
* This abbreviated alias for `parseHumanTextToRegex` maintains full functionality
* while providing a more concise interface for frequent pattern generation tasks
* and integration into larger text processing workflows.
*
* @param humanText - Descriptive text specifying the desired regex pattern behavior.
* Supports all pattern types: simple keywords, complex multi-part requirements,
* length constraints, character classes, and specialized format patterns.
* @param testValue - Optional test input for pattern validation and confidence calculation.
* Enables immediate verification that the generated pattern works as expected.
* @returns Complete `TextExtractionResult` object with comprehensive pattern data:
* - `success`: Whether text parsing and pattern generation succeeded
* - `pattern`: Ready-to-use RegExp object (undefined if generation failed)
* - `confidence`: Numerical confidence score indicating pattern reliability
* - `description`: Human-readable explanation of the pattern's matching behavior
* - `suggestions`: Actionable advice for pattern improvement or troubleshooting
*
* @example
* ```typescript
* // Compact pattern creation
* const uuid = t2r("uuid format");
* const valid = uuid.pattern?.test("550e8400-e29b-41d4-a716-446655440000");
*
* // Quick validation pipeline
* const result = t2r("alphanumeric 8-16 chars", "password123");
* console.log(`Confidence: ${result.confidence}, Valid: ${result.success}`);
*
* // Streamlined error handling
* const pattern = t2r("complex requirement").pattern || /fallback/;
* ```
*/
export declare const t2r: typeof parseHumanTextToRegex;
/**
* Rapid human-to-validation conversion with concise syntax.
* This short alias for `parseHumanTextToValidation` offers the same comprehensive
* validation rule extraction capabilities in a compact form perfect for quick
* validation setup and dynamic rule generation.
*
* @param humanText - Natural language validation requirements description.
* Handles complex validation scenarios: required fields, format constraints,
* length requirements, character composition rules, and custom validation logic.
* @param testValue - Optional input for immediate validation testing and rule verification.
* Provides instant feedback on whether the input meets the described requirements.
* @returns Full `ValidationExtractionResult` with detailed validation information:
* - `success`: Successful validation rule extraction indicator
* - `rules`: Array of structured validation rules with patterns and messages
* - `confidence`: Overall extraction confidence and rule reliability score
* - `description`: Summary of extracted validation requirements
* - `suggestions`: Helpful guidance for validation improvement
* - `allPassed`: Whether test value passes all extracted rules (when provided)
* - `caseUnPassed`: List of failed validation rule names (when test provided)
*
* @example
* ```typescript
* // Quick validation setup
* const rules = h2v("required email strong password");
*
* // Inline validation checking
* const check = h2v("phone number", "555-1234");
* if (check.allPassed) console.log("Valid phone number");
*
* // Dynamic rule generation
* const userRules = h2v(userInput).rules;
* userRules.forEach(rule => validateField(inputValue, rule));
* ```
*/
export declare const h2v: typeof parseHumanTextToValidation;
/**
* Streamlined text-to-validation rule conversion.
* This efficient alias for `parseHumanTextToValidation` provides full validation
* rule extraction capabilities with abbreviated syntax ideal for form validation,
* input checking, and automated validation pipeline creation.
*
* @param humanText - Textual description of validation constraints and requirements.
* Supports comprehensive validation scenarios: mandatory fields, format validation,
* security requirements, length constraints, and complex multi-rule validation.
* @param testValue - Optional test input for immediate rule application and validation feedback.
* Enables real-time validation testing and confidence adjustment based on actual data.
* @returns Comprehensive `ValidationExtractionResult` with complete validation context:
* - `success`: Indicates successful validation rule parsing and extraction
* - `rules`: Structured validation rules ready for implementation
* - `confidence`: Numeric confidence in the extracted validation logic
* - `description`: Clear summary of validation requirements and behavior
* - `suggestions`: Constructive feedback for validation improvement
* - `allPassed`: Overall validation status for provided test input
* - `caseUnPassed`: Specific rules that failed validation (debugging aid)
*
* @example
* ```typescript
* // Rapid form validation
* const formRules = t2v("required username email password minimum 8 characters");
*
* // Conditional validation
* const emailCheck = t2v("optional email format", userEmail);
* if (userEmail && !emailCheck.allPassed) showError("Invalid email");
*
* // Batch validation processing
* const inputs = ["required name", "phone number", "age between 18 and 100"];
* const validators = inputs.map(desc => t2v(desc));
* ```
*/
export declare const t2v: typeof parseHumanTextToValidation;
/**
* Smart pattern suggestion generator with minimal syntax.
* This compact alias for `getPatternSuggestions` provides intelligent pattern
* recommendations and guidance using the same sophisticated analysis capabilities
* in a streamlined interface perfect for user assistance and pattern discovery.
*
* @param text - Input text requiring pattern suggestions or clarification.
* Can include partial words, typos, unclear descriptions, or exploratory queries
* that need intelligent interpretation and helpful recommendations.
* @returns Curated array of relevant suggestion strings (top 5 most helpful):
* - Smart corrections for common typos and partial matches
* - Available pattern categories with descriptive keywords
* - Example usage patterns and best practices
* - General guidance for effective pattern description
*
* @example
* ```typescript
* // Quick suggestion lookup
* const help = suggest("phon");
* // Returns phone pattern suggestions and keywords
*
* // Typo assistance
* const fixes = suggest("emial addres");
* // Suggests "email address" with proper keywords
*
* // Pattern discovery
* const options = suggest("date");
* // Returns various date format options and examples
* ```
*/
export declare const suggest: typeof getPatternSuggestions;
//# sourceMappingURL=humanText.d.ts.map