Improve extract_urls

This commit is contained in:
Benedikt Heine 2018-10-31 15:03:33 +01:00
parent 65bcce652c
commit db350883cc
3 changed files with 19 additions and 18 deletions

View File

@ -63,41 +63,32 @@ void regex_teardown(void)
} }
} }
/* /* see menu.h */
* Extract all urls from a given string.
*
* Return: a string of urls separated by \n
*
*/
char *extract_urls(const char *to_match) char *extract_urls(const char *to_match)
{ {
char *urls = NULL; if (!to_match)
return NULL;
if (!regex_init()) if (!regex_init())
return NULL; return NULL;
char *urls = NULL;
const char *p = to_match; const char *p = to_match;
regmatch_t m; regmatch_t m;
while (1) { while (1) {
int nomatch = regexec(&url_regex, p, 1, &m, 0); int nomatch = regexec(&url_regex, p, 1, &m, 0);
if (nomatch) {
return urls; if (nomatch || m.rm_so == -1)
}
int start;
int finish;
if (m.rm_so == -1) {
break; break;
}
start = m.rm_so + (p - to_match); int start = m.rm_so + (p - to_match);
finish = m.rm_eo + (p - to_match); int finish = m.rm_eo + (p - to_match);
char *match = g_strndup(to_match + start, finish - start); char *match = g_strndup(to_match + start, finish - start);
urls = string_append(urls, match, "\n"); urls = string_append(urls, match, "\n");
g_free(match); g_free(match);
p += m.rm_eo; p += m.rm_eo;
} }
return urls; return urls;

View File

@ -2,7 +2,14 @@
#ifndef DUNST_MENU_H #ifndef DUNST_MENU_H
#define DUNST_MENU_H #define DUNST_MENU_H
/**
* Extract all urls from the given string.
*
* @param to_match (nullable) String to extract URLs
* @return a string of urls separated by '\n'
*/
char *extract_urls(const char *to_match); char *extract_urls(const char *to_match);
void open_browser(const char *in); void open_browser(const char *in);
void invoke_action(const char *action); void invoke_action(const char *action);
void regex_teardown(void); void regex_teardown(void);

View File

@ -8,6 +8,9 @@ TEST test_extract_urls_from_empty_string(void)
{ {
char *urls = extract_urls(""); char *urls = extract_urls("");
ASSERT_EQ_FMT(NULL, (void*)urls, "%p"); ASSERT_EQ_FMT(NULL, (void*)urls, "%p");
urls = extract_urls(NULL);
ASSERT_EQ_FMT(NULL, (void*)urls, "%p");
g_free(urls); g_free(urls);
PASS(); PASS();
} }