Skip to content

Instantly share code, notes, and snippets.

@mattolenik
Created June 23, 2018 21:15
Show Gist options
  • Save mattolenik/982462abc579e331751ea9938e0be56e to your computer and use it in GitHub Desktop.
Save mattolenik/982462abc579e331751ea9938e0be56e to your computer and use it in GitHub Desktop.
Bash regex pattern for matching bash functions
[[ 'function some_func ( ) {' =~ ^[[:blank:]]*(function[[:blank:]]+)?([\x30-\x39\x41-\x5A\x61-\x7A\xA0-\x19FF\+\-\.\^\/\?,%#_@:~]+)[[:blank:]]*\([[:blank:]]*\)[[:blank:]]*({)?$ ]]
#BASH_REMATCH results:
#0 - whole match
#1 - either 'function' or empty string
#2 - function name
#3 - either '{' or empty string
#Character ranges include pretty much all unicode and normal characters that bash will accept.
@AleixMT
Copy link

AleixMT commented Dec 28, 2022

It does not work. I am trying this:

if [[ "$text" =~ ^[[:blank:]]*(function[[:blank:]]+)?([\x30-\x39\x41-\x5A\x61-\x7A\xA0-\x19FF\+\-\.\^\/\?,%#_@:~]+)[[:blank:]]*\([[:blank:]]*\)[[:blank:]]*({)?$ ]]; then 
  echo function detected in text
else
  echo function not detected in text
fi

Any idea what might be happening? It seemed like a very powerful regex

@mattolenik
Copy link
Author

Hi there @AleixMT! I haven't looked at this in a long time but I'd have two guesses: first, make sure your version of bash is new enough, if you're on macOS the default version is 3.2 or something. If it's not that then maybe put the regex into a single-quoted string like this:

pattern='^[[:blank:]]*(function[[:blank:]]+)?([\x30-\x39\x41-\x5A\x61-\x7A\xA0-\x19FF\+\-\.\^\/\?,%#_@:~]+)[[:blank:]]*\([[:blank:]]*\)[[:blank:]]*({)?$'
if [[ "$text" =~ $pattern ]]; then 
  echo function detected in text
else
  echo function not detected in text
fi

If that doesn't work then I'm not sure...I'm not an expert with bash's regex engine, I've just learned enough to get by :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment