Regular expression enforcing message length

Viewed 73

EDIT: Answer below worked for my use case. Thanks!

I am new to writing regular expressions, and have written this to enforce commit message format.

^((US|DE|INC)[0-9]+|[A-Z]+-[0-9])

I'm using it in a Bash script, excerpted below

if [[ $MESSAGE =~ ^((US|DE|INC)[0-9]+|[A-Z]+-[0-9]) ]]; then   
  echo -e "\033[32mCommit message is valid\033[0m"  
  echo -e "$MESSAGE"`
else 
  ERROR_MESSAGE='Invalid description'
fi

This is intended the enforce the Rally story/ incident/ defect prefix.

I want to enhance this so that instead of just enforcing that the message starts with "USxxx" it also requires a commit message following a -

So the regex would only match if the message string looks like one of these: "USxxx- a short message of 8 or more characters, no upper limit required" "INCxxx- a short message of 8 or more characters, no upper limit required" "DExxx- a short message of 8 or more characters, no upper limit required"

I've tried some regex tutorials but I'm still struggling to come up with the appropriate regex, and would find it very helpful to see some draft solutions from people who know what they are doing.

1 Answers

I think this is what are you looking for:

^(US|DE|INC)[0-9]+-.{8,}$

Check out the demo at Regex101.

  • ^ is the start of the line
  • (US|DE|INC) are allowed starting variations of the string
  • [0-9]+ at least one number. If you want to enforce exactly three, use [0-9]{3} instead
    • (I see you wish to link the commit with a Jira issue that has variable length of the number, therefore + would be more appropriate)
  • - the dash is matched literally
  • .{8,} matches at least 8 characters
  • $ is the end of the line
Related