[英]Issue with RegEx in matching timestamp in filename in Linux bash
I have the following code written to check if my filename ends with some format like given below.我编写了以下代码来检查我的文件名是否以如下所示的某种格式结尾。 It is working when tested online at https://regex101.com/ but not in linux bash.
在https://regex101.com/ 上进行在线测试时,它可以正常工作,但在 linux bash 中则不能。 Please help me find out the issue.
请帮我找出问题所在。
Ex: timestamp_foramt="^[\\s\\S]+_INFT_[0-9]{8}_[0-9]{6}[.][\\w]+$" FNAME="Payments.test_INFT_20191218_075918.txt" #example if [[ ! $FNAME =~ $timestamp_foramt ]]; then echo non-format; else echo format; fi non-format
例如:
timestamp_foramt="^[\\s\\S]+_INFT_[0-9]{8}_[0-9]{6}[.][\\w]+$" FNAME="Payments.test_INFT_20191218_075918.txt" #example if [[ ! $FNAME =~ $timestamp_foramt ]]; then echo non-format; else echo format; fi non-format
timestamp_foramt="^[\\s\\S]+_INFT_[0-9]{8}_[0-9]{6}[.][\\w]+$" FNAME="Payments.test_INFT_20191218_075918.txt" #example if [[ ! $FNAME =~ $timestamp_foramt ]]; then echo non-format; else echo format; fi non-format
Please help me understand why it is not working in bash.请帮助我理解为什么它在 bash 中不起作用。 Did I commit something wrong in regex for
timestamp_foramt
?我在
timestamp_foramt
正则表达式中timestamp_foramt
误吗?
You can fix the current expression like this:您可以像这样修复当前表达式:
timestamp_foramt="^.+_INFT_[0-9]{8}_[0-9]{6}\.[[:alnum:]_]+$"
FNAME="Payments.test_INFT_20191218_075918.txt" #example
if [[ ! $FNAME =~ $timestamp_foramt ]]; then
echo 'non-format';
else
echo 'format';
fi;
See the online Bash demo .请参阅在线 Bash 演示。
Main points:要点:
[\\s\\S]
can be used in Perl and other NFA regex engines to match any character, in POSIX ERE, used in Bash, you may simply use a .
[\\s\\S]
可以在 Perl 和其他 NFA 正则表达式引擎中使用来匹配任何字符,在 POSIX ERE 中,在 Bash 中使用,您可以简单地使用.
\\w
is better written as [[:alnum:]_]
in POSIX ERE as it is more portable to match letters, digits and underscores. \\w
在 POSIX ERE 中最好写成[[:alnum:]_]
,因为它更便于匹配字母、数字和下划线。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.