2

I've got the following code and have looked at numerous examples but cannot figure out what I'm doing wrong. I know the regular expression works (see https://regex101.com/r/cB9hN1/1) - just not in my bash script. It's for a git update hook, but clearly I'm doing something wrong! Here's what I've got:

regex='ref:( |)([D]|[U])([E]|[S])(\d+)';
string="My commit ref: US2233556"

if [[ $string =~ $regex ]];
  then
    echo "[SUCCESS] Your message contains ref: for a Story or Defect."
    exit 0
else
    echo "[POLICY] Your message is not formatted correctly. Please include a \"ref: USXXXXX\" or \"ref: DEXXX\" in the commit message."
    exit 1
fi

I'd appreciate any help! Thank you!

1
  • 1
    Use regex='ref:( |)([DU])([ES])([0-9]+)';. Commented Oct 21, 2015 at 15:39

1 Answer 1

1

You should use [0-9] instead of \d and you can merge alternated character classes into single classes ([D]|[U] = [DU]):

regex='ref:( |)([DU])([ES])([0-9]+)';

See demo here

If you are not using capture groups, just remove them:

regex='ref: ?[DU][ES][0-9]+';

Here is another demo. Note that ( |) can be written shorter as ( ?) or ( )? and this way it will cause less backtracking.

Sign up to request clarification or add additional context in comments.

3 Comments

Seriously, that \d+ was my main problem?!
Yes, it was the main problem. Bash does not support the PCRE regex flavor, it is much poorer.
Oh dear! Thank you! Will accept the answer as soon as I'm allowed to!

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.