Steven Spasbo
Steven Spasbo

Reputation: 646

Regex for Git commit message

I'm trying to come up with a regex for enforcing Git commit messages to match a certain format. I've been banging my head against the keyboard modifying the semi-working version I have, but I just can't get it to work exactly as I want. Here's what I have now:

/^([a-z]{2,4}-[\d]{2,5}[, \n]{1,2})+\n{1}^[\w\n\s\*\-\.\:\'\,]+/i

Here's the text I'm trying to enforce:

AB-1432, ABC-435, ABCD-42

Here is the multiline description, following a blank 
line after the Jira issue IDs
- Maybe bullet points, with either dashes
* Or asterisks

Currently, it matches that, but it will also match if there's no blank line after the issue IDs, and if there's multiple blank lines after.

Is there anyway to enforce that, or will I just have to live with it?

It's also pretty ugly, I'm sure there's a more succinct way to write that out.

Thanks.

Upvotes: 3

Views: 7318

Answers (1)

Brian Stephens
Brian Stephens

Reputation: 5271

Your regex allows for \n as one of the possible characters after the required newline, so that's why it matches when there are multiple.

Here's a cleaned up regex:

/^([a-z]{2,4}-\d{2,5}(?=[, \n]),? ?\n?)+^\n([-\w\s*.:',]+\n)+/i

Notes:

  • This requires at least one [-\w\s*.:',] character before the next newline.
  • I changed the issue IDs to have one possible comma, space, and newline, in that order (up to one of each). Can you use lookaheads? If so, I added (?=[, \n]) to make sure the issue ID is followed by at least one of those characters.
  • Also notice that many of the characters don't need to be escaped in a character class.

Upvotes: 1

Related Questions