Home > Net >  Matching a format string defining colour codes
Matching a format string defining colour codes

Time:05-02

I want to match a format string (e.g. \033[1;42;35m) in a bash function, so the function can accept different colour setting when printing text.

Example for format is \033[1;42;35m, in general \033[NA;NB;NCm and want to match the [NA;NB;NCm part.

Am playing with

if [[ "$1" =~ \[[0123456789] ;[0123456789] ;[0123456789] m ]] ; then

The problem is the following errors

./mosc.rc: line 480: syntax error in conditional expression: unexpected token `;'
./mosc.rc: line 480: syntax error near `;['
./mosc.rc: line 480: `if [[ "\033[1;42;35m" =~ \[[0123456789] ;[0123456789] ;[0123456789] m ]] ; then'

Escaping the ; seems to work.

if [[ "$1" =~ \[[0123456789] \;[0123456789] \;[0123456789] m ]] ; then

CodePudding user response:

I would go with:

\\[0-9] (\[(?:[0-9\;] ){3}[m])

I checked in bash with your example:

bash-3.2$  [[ "\033[1;42;35m" =~ \\[0-9] \[([0-9\;] ){3}[m] ]] && echo "yes"
yes
bash-3.2$ 

Here is a link to a regex101 notebook, so you can check easily with other examples (checkout the "Explanation" panel too for a better understanding of the proposed regular expression).

CodePudding user response:

Escape both ; in your regex with a \ to prevent bash from splitting your regex in multiple commands.

  • Related