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!
birei
August 21, 2011, 8:47am
2
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
yazu
August 21, 2011, 8:54am
3
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?
birei
August 21, 2011, 9:38am
5
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
birei
August 21, 2011, 10:19am
8
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:
A piece is an atom possibly followed by a single(!) '', '+', '?', or bound. An atom followed by ' ' matches a sequence of 0 or more matches of the atom. An atom followed by '+' matches a sequence of 1 or more matches of the atom. An atom followed by '?' matches a sequence of 0 or 1 matches of the atom.
Regards,
Birei