regex - brackets and parenthesis in character-class

时间秒杀一切 提交于 2019-12-10 11:22:29

问题


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.


回答1:


You can use it like this:

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

(
)
[
]

You don't need to escape ( and ) inside a character class. Moreover if you place ] and [ right after opening [ then you don't need to escape them either.




回答2:


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.




回答3:


The most common way is to put a \ before the character, but oddly enough that doesn't seem to work for ] with grep.

If you can use Perl, do this:

% cat yourfile.txt | perl -ne 'print if(/[\[\]\(\)]/);';


来源:https://stackoverflow.com/questions/37091691/regex-brackets-and-parenthesis-in-character-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!