Created
December 19, 2019 09:27
-
-
Save totetmatt/a655546e2252d0cb9092a9875a4cbc35 to your computer and use it in GitHub Desktop.
ccc-2019.sh
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Storing the input string | |
pattern=$1 | |
string=$2 | |
# We will use 2 pointers | |
ptrPattern=0 | |
ptrString=0 | |
# Getting the lenght of pattern and string | |
lenPattern=${#pattern} | |
lenString=${#string} | |
# Stop pointer navigation when we reach end of string or pattern | |
while [ $ptrPattern -lt $lenPattern ] && [ $ptrString -lt $lenString ]; | |
do | |
matching= false | |
# if characters at the 2 pointers are matching , or if the current pattern is '.' it's a match | |
if [ ${pattern:ptrPattern:1} == '.' ] || [ ${pattern:ptrPattern:1} == ${string:ptrString:1} ] | |
then matching=true | |
else matching=false | |
fi | |
# We increase the pattern pointer by +1 | |
# Yes there is an abuse of bash as we could overflow `${pattern:ptrPattern:1}`, it won't break | |
# In other language a test to check if we are off limit would be needed | |
let ptrPattern++ | |
# Treating the special character '*' | |
if [[ ${pattern:ptrPattern:1} == "*" ]] | |
then | |
# If there was a match, we add +1 to the string pointer to test on the next loop the next character | |
# But we -1 the pattern matching as we don't know if the sequence has been finished | |
if $matching | |
then | |
let ptrPattern-- | |
let ptrString++ | |
else # we arrive a the end of a `x*` pattern, as it can be 0 character valid, we just need to check the next pattern character with the current string character | |
let ptrPattern++ | |
fi | |
else # Next pattern character is as character or `.` | |
if $matching # If it matches, we can move to next string character | |
then | |
let ptrString++ | |
else #If it didn't match, the string doesn't match the pattern, we can `exit 1` to notify error | |
exit 1 | |
fi | |
fi | |
done | |
# As '.' is wildcard for any character, the program will always be "blocked" in case of a '.*' | |
# So we need the extra step here in case there is a ".*" at the end of the pattern | |
if [[ ${pattern:ptrPattern:1} == '.' ]] | |
then | |
let ptrPattern+=2 | |
fi | |
# Check that we arrive at the end of both string, if not its not matching | |
exit $([ $ptrPattern -ge $lenPattern ] && [ $ptrString -ge $lenString ]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment