Linux下內建的regex

來源:互聯網
上載者:User

標籤:android   style   blog   http   io   color   ar   java   sp   

Linux下可直接用regex.h來支援Regex。

Android同樣也有該標頭檔,可認為Android也是支援的。

 

#include <sys/types.h>
#include <regex.h>

int regcomp(regex_t *preg, const char *regex, int cflags);

int regexec(const regex_t *preg, const char *string, size_t nmatch, regmatch_t pmatch[], int eflags);

size_t regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size);

void regfree(regex_t *preg);

 

rm_so為匹配字串起始位移(start offset),rm_eo為匹配字串的終止位移(end offset)。

typedef struct {
regoff_t rm_so;
regoff_t rm_eo;
} regmatch_t;

 

 1 #include <stdio.h> 2 #include <regex.h> 3 #include <string.h> 4  5 int main(void) 6 { 7     const char *str = "aabbccdd.com"; 8     const char *pattern = "^(.+?)\\.com$"; 9     regex_t reg;10     regmatch_t match[10];11 12     int ret = 0;13     ret = regcomp(&reg, pattern, REG_EXTENDED | REG_NEWLINE);14     if(ret != 0)15         printf("error\n");16     else17     {18         ret = regexec(&reg, str, 10, match, 0);19         if(ret != REG_NOMATCH)20         {21             int len = match[1].rm_eo - match[1].rm_so;22             char buf[1024] = {0};23             memcpy(buf, str + match[1].rm_so, len);24             printf("final buf %s\n", buf);25         }26     }27     regfree(&reg);28     return 0;29 }

regmatch_t數組用來儲存匹配的結果,該參數為數組的原因實際上是為了匹配group,其規則和Java等實現一致,若匹配成功,數組的[0]為整個匹配串,即group(0),其他為各個匹配到的組。

man regex

Linux下內建的regex

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.