why "aab" matchs "ab" when using reglar expression ?

Please see the following code, why "aab" matchs "ab" when using reglar expression ?

[saturn@saturn-pc new]$ [[ "aab" =~ "ab" ]] && echo "ok" || echo "error";
ok                                   
[saturn@saturn-pc new]$ [[ "aab" =~ "a*b" ]] && echo "ok" || echo "error";
error                          
[saturn@saturn-pc new]$ [[ "aab" =~ "a.b" ]] && echo "ok" || echo "error";
error            
[saturn@saturn-pc new]$ [[ "aab" =~ "aab" ]] && echo "ok" || echo "error";
ok
[saturn@saturn-pc new]$ 

Thanks!

Hi,

When using metacharacters in a regular expression, remove quotes:

$ [[ "aab" =~ a*b ]] && echo "ok" || echo "error";
ok
$ [[ "aab" =~ a.b ]] && echo "ok" || echo "error";
ok

Regards,
Birei

1 Like

Oh, Bash. Well, when you quote the right part of `=~' operator you get string, not a regex. And part of string is matched the whole string.

$ [[ "aab" =~ a*b ]] && echo "ok" || echo "error"
ok
$ [[ "aab" =~ a.b ]] && echo "ok" || echo "error"
ok
$ [[ "aab" =~ *ab ]] && echo "ok" || echo "error"
error

Look more about it in info bash - "Conditional Constructs".

1 Like

Thanks , but I also have a question:

[saturn@saturn-pc new]$ [[ "aab" =~ ab ]] && echo "ok" || echo "error";
ok
[saturn@saturn-pc new]$ [[ "aab" =~ "ab" ]] && echo "ok" || echo "error";
ok
[saturn@saturn-pc new]$ 

"aab" should not match ab , Can you tell me why?

Why do you think it shouldn't match?

I think that the substring 'ab' is in 'aab'.

Regards,
Birei

1 Like

I see, substring also matchs. So I need to add \b besides 'ab' .
Thanks.

[saturn@saturn-pc new]$ [[ "aabaab" =~ aaa*b ]] && echo "ok" || echo "error"
ok             !!aabaab does not contain aaab, but it matchs, why?!!

[[ "aabaab" =~ aaa*b ]] && echo "ok" || echo "error"
Here, when you include *, it means 0 or more and that is why its matching. It will basically look for aab or aaab or aaaaab etc

[[ "aabaab" =~ aaa+b ]] && echo "ok" || echo "error"
This will look for aaab, aaaab etc

regards,
Ahamed

1 Like

Althought 'ahamed101' already explained it. Execute:

$ man 7 regex

There is an explanation of how this kind of regular expression works.

Part of it says:

Regards,
Birei

Thanks all.