Skip to content

Instantly share code, notes, and snippets.

@ForeverZer0
Created February 8, 2021 19:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ForeverZer0/af50278b23d43ab7e85519d7b7906943 to your computer and use it in GitHub Desktop.
Save ForeverZer0/af50278b23d43ab7e85519d7b7906943 to your computer and use it in GitHub Desktop.
Validate URL in C (POSIX)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <regex.h>
printf("Enter the website URL:\n");
fgets(str, 100, stdin);
if (!strcmp(str, "\n")) {
printf("Empty URL ");
exit(2);
}
regex_t regex;
int reti;
char msgbuf[100];
/* Compile regular expression */
reti = regcomp(&regex, "[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,3}(/[^[:space:]]*)?$", REG_EXTENDED);
if (reti) {
fprintf(stderr, "Could not compile regex\n");
exit(3);
}
/* Execute regular expression */
reti = regexec(&regex, str, 0, NULL, 0);
if (!reti) {
puts("Valid URL");
} else if (reti == REG_NOMATCH) { //This else if always executes.
puts("Invalid URL");
exit(4);
} else {
regerror(reti, &regex, msgbuf, sizeof (msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
exit(5);
}
/* Free compiled regular expression if you want to use the regex_t again */
regfree(&regex);
@wojciechmurimi
Copy link

not working

@daniel-lucio
Copy link

the code is valid, needs a better regex

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment