Following the solution giving by http://stackoverflow.com/questions/369758/how-to-trim-whitespace-from-bash-variablehttps://stackoverflow.com/questions/369758/how-to-trim-whitespace-from-bash-variable I fixed my script this way:
echo "8:X${BASH_REMATCH[1]%"${BASH_REMATCH[1]##*[![:space:]]}"}X"
eval "$1='${BASH_REMATCH[1]%"${BASH_REMATCH[1]##*[![:space:]]}"}'"
This is a double string manipulation and the first/inner part removes everything except the trailing spaces. This string is then used to cut off the same spaces at the end of the original string.