parseRegexpPattern function
Parse regexp pattern string into pattern and replacement parts
Extracts the pattern and optional replacement from a regexp transform string. Handles escaped slashes and special characters.
Parameters
pattern- Regexp string in format/pattern/or/pattern/replacement/
Returns
A record with:
pattern- The regular expression patternreplacement- The replacement string (empty for extraction mode)
Returns null if the format is invalid (no slashes found).
Format
- Extraction:
/pattern/→(pattern: 'pattern', replacement: '') - Replacement:
/pattern/replacement/→(pattern: 'pattern', replacement: 'replacement')
Special Handling
- Escaped slashes:
\/in patterns are preserved - \ALL keyword: Converted to
^[\s\S]*$for full string matching - Escaped characters:
\/,\;are unescaped in replacement
Examples
parseRegexpPattern(r'/\d+/');
// Returns: (pattern: r'\d+', replacement: '')
parseRegexpPattern(r'/hello/world/');
// Returns: (pattern: 'hello', replacement: 'world')
parseRegexpPattern(r'/\ALL/replaced/');
// Returns: (pattern: r'^[\s\S]*$', replacement: 'replaced')
parseRegexpPattern('invalid');
// Returns: null
Implementation
({String pattern, String replacement})? parseRegexpPattern(String pattern) {
// Decode pattern after splitting to preserve escaped slashes
final parts =
pattern.split(RegExp(r'(?<!\\)/')).where((e) => e.isNotEmpty).toList();
if (parts.isEmpty) {
return null;
}
// If only pattern provided, replacement is empty
if (parts.length == 1) {
parts.add("");
}
// Decode special characters in pattern
var regexPattern = parts[0];
// Handle \ALL keyword - matches entire string including newlines
if (regexPattern.contains(r'\ALL')) {
regexPattern = regexPattern.replaceAll(r'\ALL', r'^[\s\S]*$');
}
// Decode escaped characters in replacement
final replacementStr = parts[1].replaceAll(r'\/', '/').replaceAll(r'\;', ';');
return (pattern: regexPattern, replacement: replacementStr);
}