Created
October 26, 2015 11:44
-
-
Save akkijp/1140a18dc1175e8215f7 to your computer and use it in GitHub Desktop.
c言語で正規表現で検索を行う
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <regex.h> | |
void put_n_char(const char *s, regoff_t so, regoff_t eo) | |
{ | |
const char * const ep = s + eo; | |
for(s += so; s != ep; s++) putchar(*s); | |
} | |
int main(void) | |
{ | |
regex_t reg; | |
const char *pattern = "h(ttp:(//))([[:alnum:]./]+)"; | |
regmatch_t match[5]; | |
int match_elems = sizeof match / sizeof match[0]; | |
char *s[] = { | |
"http://www.example.com", | |
"123http://www.google.com/", | |
}; | |
int s_elems = sizeof s / sizeof s[0]; | |
int i, j; | |
regcomp(®, pattern, REG_EXTENDED); | |
for(i = 0; i < s_elems; i++) { | |
if(regexec(®, s[i], match_elems, match, 0) != REG_NOMATCH) { | |
for(j = 0; j < match_elems; j++) { | |
// 注: 実装によっては regoff_t は単純な int でない可能性がある | |
printf("%2lld, %2lld: ", match[j].rm_so, match[j].rm_eo); | |
if(match[j].rm_so >= 0) | |
put_n_char(s[i], match[j].rm_so, match[j].rm_eo); | |
puts(""); | |
} | |
} | |
puts(""); | |
} | |
regfree(®); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment