Using brackets inside a character class in a regular expression

Viewed 126

I have a string:

['A', 'B']

I need to remove all ,, [, and ] characters. The final result should be

'A' 'B'

Below is a list of everything I tried, and the results

Commands I tried

user@vm:~$ echo "['A', 'B']" | sed -r 's/[\[\],]//g'
['A', 'B']

user@vm:~$ echo "['A', 'B']" | sed -r 's/[[],]//g'  # unescaped
['A', 'B']

user@vm:~$ echo "['A', 'B']" | sed -r 's/[\[\]]//g'  # removed ","
['A', 'B']

user@vm:~$ echo "['A', 'B']" | sed -r 's/[,]//g'  #removed "[" and "]"
['A' 'B']

user@vm:~$ echo "['A', 'B']" | sed -r 's/[[,]//g'  # removed "]"
'A' 'B']

Obviously, none of them worked. However, these commands did:

user@vm:~$ echo "['A', 'B']" | sed -r 's/[],[]//g'
'A' 'B'

user@vm:~$ echo "['A', 'B']" | sed -r 's/[][,]//g'
'A' 'B'

Why did this work? Differences between commands above and below:

  • The [, ] are not escaped
  • The order is different (] before [)

Why does the order matter?

1 Answers
Related