Linux下自带的regex
Linux下可直接用regex.h來支持正則表達式。
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(®, pattern, REG_EXTENDED | REG_NEWLINE); 14 if(ret != 0) 15 printf("error\n"); 16 else 17 { 18 ret = regexec(®, 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(®); 28 return 0; 29 }regmatch_t數組用來存儲匹配的結果,該參數為數組的原因實際上是為了匹配group,其規則和Java等實現一致,若匹配成功,數組的[0]為整個匹配串,即group(0),其他為各個匹配到的組。
man regex
posted on 2014-11-03 13:36 Zirconi 閱讀(...) 評論(...) 編輯 收藏轉載于:https://www.cnblogs.com/Zirx/p/4071009.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的Linux下自带的regex的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php 设置时区
- 下一篇: SvsUtil.exe生成服务文件