Regex操作以匹配不工作的空白

时间:2021-12-02 23:42:10

I'm trying to make a condition that matches any amount of spaces in a file name $f. But what I have seems to be matching everything?

我正在尝试创建一个条件来匹配文件名$f中任意数量的空格。但我所拥有的似乎是匹配一切的呢?

if [[ $f =~ [[:space:]]* ]]; then
    echo found a space
fi

This matches i-have-no-spaces.jpg as well as i have spaces.jpg

这和我没有空间。jpg和我有空间。jpg一样

1 个解决方案

#1


2  

Don't use *, it means 0 or more matches.

不要使用*,它意味着0或更多的匹配。

Use

使用

if [[ $f =~ [[:space:]] ]]; then
    echo "found a space"
fi

However in BASH, I suggest to not to use regex for this, just use glob matching with =:

但是在BASH中,我建议不要对此使用regex,只使用与=匹配的glob:

if [[ $f = *[[:space:]]* ]]; then
    echo "found a space"
fi

#1


2  

Don't use *, it means 0 or more matches.

不要使用*,它意味着0或更多的匹配。

Use

使用

if [[ $f =~ [[:space:]] ]]; then
    echo "found a space"
fi

However in BASH, I suggest to not to use regex for this, just use glob matching with =:

但是在BASH中,我建议不要对此使用regex,只使用与=匹配的glob:

if [[ $f = *[[:space:]]* ]]; then
    echo "found a space"
fi