Ruby正则表达式需求:匹配特定GitLab提交消息(排除ed/ing结尾词)
Got it, let's tackle this GitLab commit message regex requirement for Ruby. Here's a solution that fits your needs perfectly:
Solution
First, here's the Ruby regex that will match valid commit messages and reject the ones with past-tense (ed ending) or present-participle (ing ending) first words after the colon:
/\A(?:\b(MAINT|STRY-\d+): (\w+(?<!ed|ing))\b(?:\s+|\z))+\z/
If you want to restrict the first word to only letters (no numbers or underscores) for stricter validation, use this version instead:
/\A(?:\b(MAINT|STRY-\d+): ([a-zA-Z]+(?<!ed|ing))\b(?:\s+|\z))+\z/
How It Works
Let's break down the regex piece by piece to understand why it meets your requirements:
\Aand\z: These anchor the regex to the absolute start and end of the string, ensuring we validate the entire commit message (no partial matches slip through).(?: ... )+: A non-capturing group that repeats for each "prefix: content" block in your message (likeMAINT: ...orSTRY-1: ...).\b(MAINT|STRY-\d+)\b:: Matches your valid prefixes with word boundaries (\b) to avoid accidental matches (e.g.,MAINTXorSTRY-123abcwon't be recognized as valid prefixes). The trailing colon matches the required separator.(\w+(?<!ed|ing))\b: This is the core validation logic:\w+matches the first word after the colon (swap with[a-zA-Z]+if you want only letters).(?<!ed|ing)is a negative lookbehind assertion—it checks that the end of the word does NOT end withedoring, blocking the past-tense and present-participle words you want to exclude.\bensures we're checking a complete word, not just a substring.
(?:\s+|\z): Matches either whitespace between commit blocks or the end of the string, so multiple blocks are properly separated.
Testing It Out
Here's how you can implement this regex in Ruby to validate your commit messages:
# Valid message (will return true) valid_msg = "MAINT: Refactor something STRY-1: Add something STRY-2: Update something" # Invalid messages (will return false) invalid_ed_msg = "MAINT: Refactored something STRY-1: Added something STRY-2: Updated something" invalid_ing_msg = "MAINT: Refactoring something STRY-3: Adding something STRY-4: Updating something" regex = /\A(?:\b(MAINT|STRY-\d+): (\w+(?<!ed|ing))\b(?:\s+|\z))+\z/ puts regex.match?(valid_msg) # => true puts regex.match?(invalid_ed_msg) # => false puts regex.match?(invalid_ing_msg) # => false
Customization Tips
- If you use other prefixes (like
FIX,FEAT, orDOC), just add them to the prefix group:\b(MAINT|STRY-\d+|FIX|FEAT|DOC)\b: - If your first words allow hyphens (e.g.,
add-user), adjust the word matching part to[\w-]+(?<!ed|ing)—the lookbehind will still correctly check the ending of the word.
内容的提问来源于stack exchange,提问作者Moon
相关产品推荐
相关产品推荐

