Skip to main content

Regular Expression Matching

Definition​

The Regular Expression Matching is a computational method used to determine whether a given string matches a pattern defined by a regular expression. It involves parsing the regular expression and the input string, and then applying matching rules iteratively to determine if there's a match.

Practice​

isMatch(input: string, pattern: string) -> boolean:
# Start matching from the beginning of input and pattern
return matchHelper(0, 0)

# Function to recursively match the pattern with the input string
function matchHelper(inputIndex: integer, patternIndex: integer) -> boolean:
# Base case: both input and pattern are exhausted
if inputIndex == length(input) and patternIndex == length(pattern):
return true
# Base case: pattern is exhausted, but input is not
if patternIndex == length(pattern):
return false
# Check if the current characters match or pattern has wildcard
currentMatch = inputIndex < length(input) and (input[inputIndex] == pattern[patternIndex] or pattern[patternIndex] == '.')
# Check if next character in pattern is a quantifier
if patternIndex + 1 < length(pattern) and pattern[patternIndex + 1] == '*':
# If pattern has a wildcard, try matching input with pattern after wildcard
return matchHelper(inputIndex, patternIndex + 2) or (currentMatch and matchHelper(inputIndex + 1, patternIndex))
# If characters match, move to next character in both input and pattern
if currentMatch:
return matchHelper(inputIndex + 1, patternIndex + 1)
return false