regex - 为什么 grep 不匹配 "\<\-v\>"
问题描述
我想在 gcc 的手册页中查找选项“-v”。
man gcc | grep -w '\-v'
作品。但我想使用正则表达式。
但是,正如我所料,以下行与单词开头的“-v”不匹配:
grep '\<-v' <<<$'-v'
为什么?
解决方案
单词边界转义序列与选项略有不同-w
,从man grep
-w, --word-正则表达式
仅选择那些包含构成整个单词的匹配项的行。测试是匹配的子字符串必须在行首,或者前面有一个非单词组成字符。同样,它必须位于行尾或后跟非单词组成字符。构成单词的字符是字母、数字和下划线。
而正则表达式中的单词边界只有在有单词字符的情况下才会起作用
$ # this fails because there is no word boundary between space and +
$ # assumes \b is supported, like GNU grep
$ echo '2 +3 = 5' | grep '\b+3\b'
$ # this works as -w only ensures that there are no surrounding word characters
$ echo '2 +3 = 5' | grep -w '+3'
2 +3 = 5
$ # doesn't work as , isn't at start of word boundary
$ echo 'hi, 2 one' | grep '\<, 2\>'
$ # won't match as there are word characters before ,
$ echo 'hi, 2 one' | grep -w ', 2'
$ # works as \b matches both edges and , is at end of word after i
$ echo 'hi, 2 one' | grep '\b, 2\b'
hi, 2 one
推荐阅读
- prestashop - Probem 在同一个域上安装两个 prestashop 1.7 商店
- macos - 什么会导致 .NET Core 二进制文件加载本机库,然后引发 DllNotFoundException?
- go - golang模板中字符串切片的范围
- python - 如何使类 JSON 可序列化以在 Django 会话中使用
- c# - 错误 CS0266 无法将类型“double”隐式转换为“int”
- haskell - 使用 Tagless Final 方法时的类型变量不明确
- machine-learning - 超过 1000 个课程的 Keras 迁移学习
- javascript - 有没有办法在 javascript 类中创建一个方法来创建变量?
- javascript - 编写此代码的更好方法?我试图避免双重返回语句
- django - Django Unittest 无法运行 TypeError: isinstance() arg 2 must be a type or tuple of types on a machine but not others