feat: Initial commit
This commit is contained in:
94
Laboratorio 1/Esercizio 1/main.c
Normal file
94
Laboratorio 1/Esercizio 1/main.c
Normal file
@@ -0,0 +1,94 @@
|
||||
// Laboratorio 1 - Esercizio 1
|
||||
// Matteo Schiff - s295565
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
|
||||
char *cercaRegexp(char *src, char *regexp);
|
||||
|
||||
// NOTE: regexp has to be incremented after calling this function
|
||||
bool checkChar(char src, char **regexp)
|
||||
{
|
||||
switch (**regexp)
|
||||
{
|
||||
case '.':
|
||||
return true;
|
||||
case '[':
|
||||
(*regexp)++;
|
||||
int negate = **regexp == '^';
|
||||
|
||||
if (negate)
|
||||
(*regexp)++;
|
||||
|
||||
do
|
||||
{
|
||||
if (src == **regexp) {
|
||||
while (**regexp != ']')
|
||||
(*regexp)++;
|
||||
return !negate;
|
||||
}
|
||||
(*regexp)++;
|
||||
} while (**regexp != ']');
|
||||
|
||||
return negate;
|
||||
case '\\':
|
||||
(*regexp)++;
|
||||
if (**regexp == 'a') {
|
||||
return islower(src);
|
||||
} else if (**regexp == 'A') {
|
||||
return isupper(src);
|
||||
}
|
||||
return false; // NOTE: regex is not valid
|
||||
default:
|
||||
return src == **regexp;
|
||||
}
|
||||
}
|
||||
|
||||
bool matchSubstring(char *src, char *regexp)
|
||||
{
|
||||
char *cur_s = src;
|
||||
char *cur_meta = regexp;
|
||||
|
||||
while (*cur_meta != 0)
|
||||
{
|
||||
// match failed if regex check is false or if we reached the end
|
||||
// of the string without reaching the end of the regex
|
||||
if (*cur_s == 0 || !checkChar(*cur_s, &cur_meta))
|
||||
return false;
|
||||
|
||||
cur_s++;
|
||||
cur_meta++;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
char *searchRegexp(char *src, char *regexp)
|
||||
{
|
||||
char *cur_s = src;
|
||||
|
||||
while (*cur_s != 0)
|
||||
{
|
||||
if (matchSubstring(cur_s, regexp))
|
||||
return cur_s;
|
||||
cur_s++;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(int argc, char ** argv) {
|
||||
if (argc != 3) {
|
||||
puts("USAGE: ./esercizio1 string regexp");
|
||||
return 1;
|
||||
}
|
||||
|
||||
char * substr = searchRegexp(argv[1], argv[2]);
|
||||
|
||||
if (!substr) {
|
||||
puts("No matches");
|
||||
} else {
|
||||
puts(substr);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user