Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux 正則表達式完整參考:基本/擴展語法元字符對照表、grep/egrep/fgrep 三劍客用法詳解

編輯:關於 Linux

正則表達式是 Linux 文字處理的通用語言。本文整理基本正則 (BRE) 與擴展正則 (ERE) 元字符差異、grep/egrep/fgrep 三種模式適用場景,並提供 man 7 regex 深入查閱路徑。

基本正則元字符表

擴展正則元字符表

grep 三劍客對比

基本正則 (BRE) vs 擴展正則 (ERE) 關鍵差異

功能BRE (grep/sed)ERE (egrep/awk)
分組捕獲\(...\)(...)
或邏輯不支援|
量詞\{m,n\}{m,n}
單字邊界\< \>\b
反向引用\1 \2\1 \2

grep 三劍客選型指南


grep   "pattern" file      # BRE,預設
egrep  "pat1|pat2" file    # ERE,支援 | + ? {} 等
fgrep  "fixed_string" file # 固定字串,最快,無正則解析

常用元字符速查 (ERE 為主)

  • ^ $ . * + ? {m,n} [abc] [^abc] | () \b \d \w \s
  • 轉義字元:\n \t \r \\ \. 等。

實戰範例


# IP 地址 (ERE)
egrep '\b((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\b' access.log

# Email 簡易驗證
grep -E '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$' users.txt

# 固定字串高速搜尋
fgrep "ERROR: Connection timeout" /var/log/app.log

熟練正則表達式,即可在海量日誌、程式碼、資料中精準提取所需資訊。

Copyright © Windows教程網 All Rights Reserved