nullByteMe
nullByteMe

Reputation: 6391

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.

Upvotes: 3

Views: 845

Answers (3)

iruvar
iruvar

Reputation: 23374

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:]]*\])'

Upvotes: 1

rkh
rkh

Reputation: 863

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...

Upvotes: 2

Ωmega
Ωmega

Reputation: 43663

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

Upvotes: 2

Related Questions