command line – How to check allowed characters in bash with regex
I want to use regex for checking only three allowed characters: “[0-9]” and “.” and “/“.
Note: The test case is an ipv4/ipv6 address but I don’t want to check the number in the range [0-255], I only want to check allowed characters in the input variable.
I use “|” as the “or” expression, and combine all the three allowed characters with “|“, and finally add “+” in the last for make sure at less one allowed character must exist in the input variable.
Here is the test bash script:
test_ipv4_address="127.0.0.1/24"
test_wrong_ipv4_address="127.0.0.1#24"
test_ipv6_address="::1/128"
allowed_characters="([0-9]|\.|\/)+"
[[ "$test_ipv4_address" =~ $allowed_characters ]] && echo "yes, $test_ipv4_address is allowed"
[[ "$test_wrong_ipv4_address" =~ $allowed_characters ]] && echo "yes, $test_wrong_ipv4_address is allowed"
[[ "$test_ipv6_address" =~ $allowed_characters ]] && echo "yes, $test_ipv6_address is allowed"
Here is the output:
yes, 127.0.0.1/24 is allowed
yes, 127.0.0.1#24 is allowed
yes, ::1/128 is allowed
Here is the expected output:
yes, 127.0.0.1/24 is allowed
What’s wrong in my regex? And how to fix?
Read more here: Source link
