正则表达式 - 字符中的方括号和括号 - class
regex - brackets and parenthesis in character-class
我想匹配这些字符:正则表达式中 class 字符中的 [ ] ( ),我该怎么做?
echo 'some text (some text in parenthesis) [some other in brackets]' | grep '[\[\]\(\)]'
这个不匹配任何字符。
你可以这样使用它:
echo 'some text (some text in paranthesis) [some other in brackets]' | grep -o '[][()]'
(
)
[
]
您不需要在字符 class 内转义 (
和 )
。此外,如果您在打开 [
之后立即放置 ]
和 [
,那么您也不需要转义它们。
最常见的方法是在字符前加一个 \,但奇怪的是这似乎不适用于 ] 和 grep。
如果您会使用 Perl,请执行以下操作:
% cat yourfile.txt | perl -ne 'print if(/[\[\]\(\)]/);';
仅供参考:
根据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.
另外,你可以看到(
、[
和)
在括号表达式中并不特殊
因为 ]
在你的 '[\[\]\(\)]'
括号表达式 模式不是第一个字符,它结束模式,和下一个 ]
创建了一个不完整的括号表达式。
我想匹配这些字符:正则表达式中 class 字符中的 [ ] ( ),我该怎么做?
echo 'some text (some text in parenthesis) [some other in brackets]' | grep '[\[\]\(\)]'
这个不匹配任何字符。
你可以这样使用它:
echo 'some text (some text in paranthesis) [some other in brackets]' | grep -o '[][()]'
(
)
[
]
您不需要在字符 class 内转义 (
和 )
。此外,如果您在打开 [
之后立即放置 ]
和 [
,那么您也不需要转义它们。
最常见的方法是在字符前加一个 \,但奇怪的是这似乎不适用于 ] 和 grep。
如果您会使用 Perl,请执行以下操作:
% cat yourfile.txt | perl -ne 'print if(/[\[\]\(\)]/);';
仅供参考:
根据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.
另外,你可以看到(
、[
和)
在括号表达式中并不特殊
因为 ]
在你的 '[\[\]\(\)]'
括号表达式 模式不是第一个字符,它结束模式,和下一个 ]
创建了一个不完整的括号表达式。