Re: [問題] sed , grep 匹配問題

看板RegExp作者 (System hacked)時間4年前 (2020/02/24 23:43), 編輯推噓1(100)
留言1則, 1人參與, 4年前最新討論串2/3 (看更多)
你的問題是 GNU 的實做問題,如下。 ※ 引述《ericshei (ericshei)》之銘言: : 請教,我不理解為什麼^..*,[1-9]*,\+在如下grep , sed的結果是match的? : $ echo '11162,1,2020-02-17 19:59:31:696,+000000000 00:01:39.097' | grep '^..*,[1-9]*,\+' : 11162,1,2020-02-17 19:59:31:696,+000000000 00:01:39.097 我沒翻到 2.20 的 manual,但這是 2.16 的 grep: https://manpages.ubuntu.com/manpages/trusty/man1/grep.1.html Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). 這是 2.24 的 grep: https://manpages.ubuntu.com/manpages/xenial/man1/grep.1.html Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). 基本上是一樣的,所以我猜 grep 2.20 也是一樣的。 雖然 GNU grep 都是宣稱實做 POSIX 的 Basic Regular Expressions (BRE),但 GNU grep 很雞婆的加上了特殊的延伸。 所以這邊的 ,\+ 的部份是一個或多個逗點的意思,所以會 match。 : $ echo '11162,1,2020-02-17 19:59:31:696,+000000000 00:01:39.097' | sed 's/^..*,[1-9]*,\+/REPLACED/g' : REPLACED2020-02-17 19:59:31:696,+000000000 00:01:39.097 同樣的道理,雖然 GNU sed 宣稱也是 BRE,但 GNU sed 有自己實做了 GNU extension: https://www.gnu.org/software/sed/manual/html_node/Regular-Expressions.html \+ As *, but matches one or more. It is a GNU extension. 所以後面的 ,\+ 的部份也是一個或多個的意思,所以 "11162,1," 被換掉了。 -- Resistance is futile. https://blog.gslin.org/ & <gslin@gslin.org> -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.116.104.21 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/RegExp/M.1582559019.A.A93.html

02/26 09:54, 4年前 , 1F
非常感謝您的說明
02/26 09:54, 1F
文章代碼(AID): #1UK-yhgJ (RegExp)
文章代碼(AID): #1UK-yhgJ (RegExp)