expr 充當簡單 regexp 工具

有時候會需要用一下簡單的 regexp 處理字串, 以前我會因此用 perl -ne …, 後來太久沒寫 perl 又忘了語法, 遇到這種情況就覺得頗困擾的。今天在讀別人的 shell script 時發覺 expr 竟然也有基本的 regexp 功能!!

以下是 man expr 的部份內容:
STRING : REGEXP
Pattern matches return the string matched between \( and \) or null; if \( and \) are not used, they return the number of characters matched or 0.
附上相關例子:
$ expr “hello world” : “hello.*”
11
$ expr “hello world” : “hello”
5
$ expr “hello world” : “hello \(.*\)”
world
有了 expr, 以後湊指令方便多啦