1

I'm trying to write a simple regex in a shell script and I can't get it to match anything. I'm not sure if my regex is incorrect or my shell code is incorrect

#!/bin/sh
#
# This hook verifies that the commit message contains a reference to a tfs item

# Regex to validate a string contains "#" and 4 or 5 digits
regex="/#\d{4,5}/"
param=$1
echo "param = $param"
echo "regex = $regex"

if [[ $param =~ $regex ]]; then
  output="yes"
else
  output="no"
fi

echo "output = $output"

...

I'm running my script with $ ./myscript "#1234" and $ ./myscript "asdf #1234 asdf" and those should both output "yes"

1 Answer 1

2
regex="/#\d{4,5}/"

Is not correct regex for BASH. You can use:

regex="#[0-9]{4,5}"
  • No regex delimiters in BASH regex
  • \d, \w properties are not supported
Sign up to request clarification or add additional context in comments.

10 Comments

This doesn't quite work. It also also passes with $ ./myscript "asdf "#123456789"...which means my regex is not quite right.
You need to add a $ at the end to anchor the match if that's what you want. A regex will match anywhere in a longer string unless you anchor it.
@tripleee if I add a $ at the end that makes it so $ ./myscript "asdf #1234 asdf" doesn't work. I basically want to allow a hashtag followed by 4 or 5 digits anywhere in the string.
So it can be followed by anything as long as it's not a number? Then "#[0-9]{4,5}($|[^0-9])"
It could be followed by a number again. So this would be allowed asdf #1234 1 also. I just want to require that hashtag followed by 4 or 5 digits exists anywhere in the string.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.