Created
February 8, 2021 19:34
-
-
Save ForeverZer0/af50278b23d43ab7e85519d7b7906943 to your computer and use it in GitHub Desktop.
Validate URL in C (POSIX)
This file contains 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 <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(®ex, "[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(®ex, 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, ®ex, 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(®ex); |
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
not working