GUN CRegex

來源:互聯網
上載者:User

最近項目中要處理文本,因此就用了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.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.