最近項目中要處理文本,因此就用了gun的Regex,它是posix風格的..我們一般使用的都是perl風格的,所以一開始使用可能會有一些不習慣.詳細的區別可以在wiki上看到:
http://en.wikipedia.org/wiki/Regular_expression
標頭檔是regex.h可以在裡面看到他所提供的介面.這裡主要是3個函數和一個結構體:
引用
int regcomp (regex_t *compiled, const char *pattern, int cflags)
int regexec (regex_t *compiled, char *string, size_t nmatch, regmatch_t matchptr [], int eflags)
void regfree (regex_t *compiled)
typedef struct {
regoff_t rm_so;
regoff_t rm_eo;
} regmatch_t;
regcomp會將參數pattern編譯為compiled,也就是講字串編譯為Regex.
而參數cflags可以是下面1種或者幾種的組合:
REG_EXTENDED
使用 擴充的 posix Regular Expressions.
REG_ICASE
忽略大小寫
REG_NOSUB
不儲存匹配結果,只返回是否匹配成功.
REG_NEWLINE
可以匹配換行.
regexec執行匹配.compiled為剛才編譯好的Regex,string為將要匹配的字串,nmatch為後面的結構體數組的長度 (regmatch_t).matchptr為regmatch_t的一個數組(也就是儲存著像perl裡面的$0,$1這些的位置,也就是).而 eflag參數則可以是下面中的1個或多個.
REG_NOTBOL
會講^作為一個一般字元來匹配,而不是一行的開始
REG_NOTEOL
會講$作為一個一般字元來匹配,而不是一行的結束
regfree每次用完之後需要釋放這個Regex.compiled為需要釋放的Regex.
regmatch_t 中的rm_so為匹配字元的開始位置,rm_eo為結束位置.
說了這麼多,其實使用很簡單的:
引用
POSIX Regexp Compilation: Using regcomp to prepare to match.
Flags for POSIX Regexps: Syntax variations for regcomp.
Matching POSIX Regexps: Using regexec to match the compiled pattern that you get from regcomp.
Regexp Subexpressions: Finding which parts of the string were matched.
Subexpression Complications: Find points of which parts were matched.
Regexp Cleanup: Freeing storage; reporting errors.