You can look for an opening bracket and clear with the K
escape sequence. Then, match up to the closing bracket:
$ grep -Po '[K[^]]*' <<< "32432423 jkhkjh [234] hkjh32 2342342"
234
Note you can omit the -P
(Perl extended regexp) by saying:
$ grep -o '[.*]' <<< "32432423 jkhkjh [234] hkjh32 2342342"
[234]
However, as you see, this prints the brackets also. That's why it is useful to have -P
to perform a look-behind and look-after.
You also mention ?
in your regexp. Well, as you already know, *?
is to have a regex match behave in a non-greedy way. Let's see an example:
$ grep -Po '[.*?]' <<< "32432423 jkhkjh [23]4] hkjh32 2342342"
[23]
$ grep -Po '[.*]' <<< "32432423 jkhkjh [23]4] hkjh32 2342342"
[23]4]
With .*?
, in [23]4]
it matches [23]
. With just .*
, it matches up to the last ]
hence getting [23]4]
. This behaviour just works with the -P
option.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…