Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex - brackets and parenthesis in character-class

I would like to match these characters: [ ] ( ) in a character class in a regex, how can I do that?

echo 'some text (some text in parenthesis) [some other in brackets]' | grep '[\[\]\(\)]'

This one doesn't match any character.

like image 419
nagy.zsolt.hun Avatar asked Sep 02 '25 02:09

nagy.zsolt.hun


2 Answers

You can use it like this:

echo 'some text (some text in paranthesis) [some other in brackets]' |
grep -o '[][()]'

(
)
[
]

Please note that:

  • If ] and [ are placed right after opening [ in a bracket expression then they are treated as literals ] or [.
  • That may be an optional ^ at the first place for negation before ] or [
  • You don't need to escape ( and ) inside a bracket expression.
like image 126
anubhava Avatar answered Sep 05 '25 16:09

anubhava


Just FYI:

Accoding to the grep documentation, section 3.2 Character Classes and Bracket Expressions:

Most meta-characters lose their special meaning inside bracket expressions.

‘]’
ends the bracket expression if it’s not the first list item. So, if you want to make the ‘]’ character a list item, you must put it first.

Also, you can see that (, [ and ) are not special in the bracket expressions.

Since ] in your '[\[\]\(\)]' bracket expression pattern is not the first character, it ends the pattern, and the next ] created an incomplete bracket expression.

like image 32
Wiktor Stribiżew Avatar answered Sep 05 '25 16:09

Wiktor Stribiżew