首页 > 解决方案 > 正则表达式强制消息长度

问题描述

编辑:下面的答案适用于我的用例。谢谢!

我是编写正则表达式的新手,并且写了这个来强制提交消息格式。

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

我在 Bash 脚本中使用它,摘录如下

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

这是为了强制执行 Rally 故事/事件/缺陷前缀。

我想增强这一点,以便不仅强制消息以“USxxx”开头,还需要在-

因此,只有当消息字符串看起来像以下之一时,正则表达式才会匹配:“USxxx- 8 个或更多字符的短消息,不需要上限”“INCxxx-8 个或更多字符的短消息,不需要上限” “DExxx-8个或更多字符的短消息,不需要上限”

我已经尝试了一些正则表达式教程,但我仍然在努力想出合适的正则表达式,并且会发现从知道自己在做什么的人那里看到一些草稿解决方案非常有帮助。

标签: regexbash

解决方案


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

推荐阅读