Regular expression: Returns the characters inside parentheses

Regular expression: Returns the characters inside parentheses … here is a solution to the problem.

Regular expression: Returns the characters inside parentheses

I can’t seem to be able to get the value inside parentheses using grep.

echo "(this is a string)" | grep -Eo '[a-z ]*'

Ideally, it should return the value inside parentheses, “this is a string”, and not return anything. Does anyone know the explanation?

Solution

This grep with -P (perl regular expression) is valid:

echo "foo (this is a string) bar" | grep -Po '\(\K[^)]*'
this is a string

Or use awk:

echo "foo (this is a string) bar" | awk -F '[()]+' '{print $2}'
this is a string

Or use sed:

echo "foo (this is a string) bar" | sed 's/^.*(\(.*\)*).*$/\1/'
this is a string

Related Problems and Solutions