example.txt ~ $ grep "hello$" example.txt hello-6ren">
gpt4 book ai didi

regex - 行尾字符 ($) 在方括号内不起作用

转载 作者:行者123 更新时间:2023-12-02 02:38:04 26 4
gpt4 key购买 nike

$ 放在方括号内对于 grep 不起作用。

~ $ echo -e "hello\nthere" > example.txt
~ $ grep "hello$" example.txt
hello
~ $ grep "hello[$]" example.txt
~ $

这是 grep 中的错误还是我做错了什么?

最佳答案

这就是它应该做的。

[$]

...定义匹配一个字符 $ 的字符类。

因此,这将匹配包含 hello$ 的行。

<小时/>

参见the POSIX RE Bracket Expression definition对于要求如此的正式规范。引用完整的定义:

A bracket expression (an expression enclosed in square brackets, "[]" ) is an RE that shall match a single collating element contained in the non-empty set of collating elements represented by the bracket expression.

因此,任何括号表达式都匹配单个元素。

<小时/>

此外,在 the BRE Anchoring Expression definition:

  1. A dollar sign ( '$' ) shall be an anchor when used as the last character of an entire BRE. The implementation may treat a dollar sign as an anchor when used as the last character of a subexpression. The dollar sign shall anchor the expression (or optionally subexpression) to the end of the string being matched; the dollar sign can be said to match the end-of-string following the last character.

因此 - 从 BRE 开始,grep 默认情况下识别不带参数的正则表达式格式 - 如果 $ 不在表达式末尾,则它是不需要被识别为 anchor 。

关于regex - 行尾字符 ($) 在方括号内不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32316254/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com