为什么我的RegEx总是在Bash中返回“ true”?

时间:2019-11-08 12:44:40

标签: regex bash

作为bash脚本的一部分,我试图构建一个过滤器,该过滤器会在传递不正确的文件名时退出脚本:

if [[ ! $1 =~ [^DCS-932L20\d{14}(\.[jJ][pP][gG])$] ]]; then 
   echo "'$1' is not a valid name"
   exit 1
fi

在调试器中测试RegEx时,它会匹配正确的字符串,例如:DCS-932L2019110607132405.jpg

但是在bash脚本中实现时,IF语句始终返回true

当我将RegEx缩短为[^DCS-]时,一切似乎都可以正常工作,但是仅添加'9'([^DCS-9])就足以使该语句再次返回true < / p>

我尝试转义([^DCS\-9][^DCS-\9]

我尝试使用引号(["^DCS-9"]['^DCS-\9']

我尝试了这些的组合。

对于bash和RegEx来说,我都是一个新手,所以如果有人可以解释我的错,我将非常感谢

1 个答案:

答案 0 :(得分:3)

您通过用正括号将正则表达式包裹起来,从而在正则表达式中创建了一个括号表达式。此外,Bash POSIX ERE正则表达式不支持http.addFilterBefore(corsFilter(),SessionManagementFilter.class).httpBasic().authenticationEntryPoint(samlEntryPoint()); http.csrf().disable(); http.addFilterBefore(metadataGeneratorFilter(),ChannelProcessingFilter.class).addFilterAfter(samlFilter(),BasicAuthenticationFilter.class); http.authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll().antMatchers("/error").permitAll().antMatchers("/saml/**").permitAll().anyRequest().authenticated(); 速记字符类,您需要使用\d[0-9]

最好在[[:digit:]]之前声明正则表达式并用作无引号的变量:

=~

查看online Bash demo

请注意,此处不需要分组括号,因此将其删除。