Sage-Code Laboratory
index<--

Regular Expressions

A regular expression is some sequence of characters that represents a pattern. Actually the regular expressions is a secret language used for comparing a string with a pattern. It can be used for search or validations.

Bash has builtin regular expressions. You can compare a string with a reqular expression by using specific operator "=~". The challange is to build the regular expression pattern. In next example we check if a particular input character is digit or other symbol.

digit.sh
#!/bin/bash
read -p "enter a symbol:" symbol

if [[ $symbol =~ [0-9] ]] 
then
    echo "$symbol is a digit"
elif [[ $symbol =~ [A-Za-z] ]] 
then
    echo "$symbol is a letter"
else
    echo "$symbol is special \
    character"
fi
console
~/bash-repl$ bash symbol.sh
enter a symbol:6
6 is a digit
~/bash-repl$ bash symbol.sh
enter a symbol:A
A is a letter
~/bash-repl$ bash symbol.sh
enter a symbol:@
@ is special character
~/bash-repl$ bash symbol.sh
enter a symbol:*
* is special character
~/bash-repl$ 

Some tricks

example
#!/bin/bash
echo -n "Enter: > "
read num
if [[ $num =~ ^[0-9]+$ ]]
then
    echo Decimal
elif [[ $num =~ ^[A-Fa-f0-9]+$ ]]
then
    echo Hexadecimal
else
    echo Non-numeric
fi
console
~/bash-repl$ bash validx.sh
Enter: > 145
Decimal
~/bash-repl$ bash validx.sh
Enter: > AB13
Hexadecimal
~/bash-repl$ bash validx.sh
Enter: > abcff355           
Hexadecimal
~/bash-repl$ bash validx.sh
Enter: > #123.5
Non-numeric
~/bash-repl$ 

Advanced Regex Usage

You can learn and build regular expressions on a free website that I have found and used myself to learn some tricks. Regular expressions are very powerful but need a lot of practice to make or understand complex patterns.

External tool: https://regexr.com/

Note: You can use regular expressions to search in output a command by using other commands that accept as a parameter regular expressions. Check these two special commands: sed and grep. We will prepare examples fot these commands.


Read next: File handling