[英]Bash Script Regular Expression Issue
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.我知道正则表达式有效(请参阅https://regex101.com/r/cB9hN1/1 ) - 只是不在我的 bash 脚本中。 It's for a git update hook, but clearly I'm doing something wrong!这是一个 git update 钩子,但显然我做错了什么! 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!谢谢!
You should use [0-9]
instead of \\d
and you can merge alternated character classes into single classes ( [D]|[U]
= [DU]
):您应该使用[0-9]
而不是\\d
并且您可以将交替的字符类合并为单个类( [D]|[U]
= [DU]
):
regex='ref:( |)([DU])([ES])([0-9]+)';
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.这样它会减少回溯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.