Regex to match string between brackets

Regex to match string between brackets

I have a regex that properly returns this:
[a1]
[b892jklas]
[klaj218349]
[alllasd]

But I just want to match and return:
a1
b892jklas
klaj218349
alllasd

I’m using the following command
cmd | grep -i -o -E ‘\[[[:alnum:]]\]’

But I don’t know how to exclude the brackets from the result.

Solutions/Answers:

Solution 1:

grep -Po '(<=\[)[a-zA-Z0-9]+(?=\])'

Solution 2:

UPDATE:

tr -d '[]' also works (Thanks @1_CR for the comment)

ORIGINAL POST:

... | tr -s "[" "" | tr -s "]" "" is the simplest solution. You can also used sed

Solution 3:

If GNU grep is an option (also this should have been compiled against a recent version of libpcre.so for \K to work)

grep -oP '\[[[:space:]]*\K[[:alnum:]]+(?=[[:space:]]*\])'

References

Loading...