[Progetto] [C] Espressioni regolari e fscanf()

Linguaggi di programmazione: php, perl, python, C, bash e tutti gli altri.
daniele87
Prode Principiante
Messaggi: 146
Iscrizione: lunedì 12 ottobre 2009, 22:42

[Progetto] [C] Espressioni regolari e fscanf()

Messaggio da daniele87 »

Ciao,
ho la necessità di dividere una stringa presa in input da file usando la funzione fscanf.
Questo perché ogni singola riga del file è formata da un determinato pattern.
Ad esempio se uso un pattern formato da 3 stringhe cosi definito:
OggettoMessaggio:Messaggio
potrei avere una situazione del genere:
messaggio di prova: ciao a tutti

fscanf appena incontra uno spazio in una stringa, si ferma e copia i caratteri che ha trovato nella stringa di destinazione che ho indicato, quindi ad esempio anziché ottenere "messaggio di prova" otterrò solo "messaggio", il che non mi va bene.
So che è possibile sfruttare le espressioni regolari per poter risolvere la situazione, anche se non so bene come usarle.
Quello che mi servirebbe è creare una RE che (stranamente) accetta stringhe formate da qualsiasi carattere.
Come si potrebbe fare?

Grazie
Avatar utente
crap0101
Rampante Reduce
Rampante Reduce
Messaggi: 8242
Iscrizione: martedì 30 ottobre 2007, 6:33
Desktop: LXDE
Distribuzione: Ubuntu 18.04.1 LTS
Sesso: Maschile
Località: TO
Contatti:

Re: [Progetto] [C] Espressioni regolari e fscanf()

Messaggio da crap0101 »

un esempio a titolo puramente dimostrativo :):

Codice: Seleziona tutto

#include <stdio.h>
#include <sys/types.h>
#include <regex.h>


int
main (int argc, char **argv)
{
  if (argc < 2)
    {
      printf ("USAGE: %s <STRING>\n", *argv);
      return 1;
    }
  regex_t reg;
  int res;
  char buff[1000];
  char pattern[] = "^[[:alpha:]]+:[[:space:]]?[[:alpha:]]+";
  if ((res = regcomp (&reg, pattern, REG_EXTENDED)) != 0)
    {
      regerror(res, &reg, buff, sizeof buff);
      fprintf (stderr, "regcomp: %s (%s)\n", buff, pattern);
      return 1;
    }
  if ((res = regexec (&reg, *++argv, 0, NULL, 0)) != 0)
    {
      regerror(res, &reg, buff, sizeof buff);
      fprintf (stderr, "%s (%s)\n", buff, pattern);
      return 1;
    }
  else
    printf ("match!\n");
  return 0;
}
per cui:
crap0101@trisquel:~/test$ gcc -Wall foo.c -o foo
crap0101@trisquel:~/test$ ./foo 'OggettoMessaggio:ll'
match!
crap0101@trisquel:~/test$ ./foo 'OggettoMessaggio: ll'
match!
crap0101@trisquel:~/test$ ./foo 'OggettoMessaggio: 1ll'
No match (^[[:alpha:]]+:[[:space:]]?[[:alpha:]]+)
crap0101@trisquel:~/test$ ./foo 'OggettoMessaggio12: ll'
No match (^[[:alpha:]]+:[[:space:]]?[[:alpha:]]+)
crap0101@trisquel:~/test$
http://www.gnu.org/ http://boinc.berkeley.edu/ http://www.python-it.org/
- Ricorda le ultime parole di suo padre: «Sta' alla larga dalle chiese, figlio. La sola cosa per cui hanno la chiave è il merdaio. E giurami che non porterai mai un distintivo della legge» - W.S. Burroughs
peppec22
Prode Principiante
Messaggi: 1
Iscrizione: martedì 19 maggio 2015, 19:01
Desktop: ubuntu
Distribuzione: Ubuntu 14.04.2 LTS x86_64
Sesso: Maschile

Re: [Progetto] [C] Espressioni regolari e fscanf()

Messaggio da peppec22 »

Ciao ragazzi, vorrei sapere se qualcuno mi potrebbe spiegare questo codice, soprattutto non riesco a capire il simbolino ® cosa sta a significare.
Avatar utente
crap0101
Rampante Reduce
Rampante Reduce
Messaggi: 8242
Iscrizione: martedì 30 ottobre 2007, 6:33
Desktop: LXDE
Distribuzione: Ubuntu 18.04.1 LTS
Sesso: Maschile
Località: TO
Contatti:

Re: [Progetto] [C] Espressioni regolari e fscanf()

Messaggio da crap0101 »

il messaggio è abbastanza vecchio, penso sia per via del cambiamento della piattaforma del forum (che interpreta quella sequenza come ® mentre in realtà è &reg .

Riguardo al codice... in effetti a rileggerlo non ho capito bene perchè l'ho scritto :-D
Nel senso che non è proprio completo, dovrebbe essere più tipo:

Codice: Seleziona tutto

#include <stdio.h>
#include <sys/types.h>
#include <regex.h>
#include <string.h>


int
main (int argc, char **argv)
{
  if (argc < 2)
    {
      printf ("USAGE: %s <STRING>\n", *argv);
      return 1;
    }
  char *str = argv[1];
  char mstr[100];
  size_t msize;
  regex_t reg;
  size_t nmatch = 3;
  regmatch_t rmatch[3];
  int res;
  char buff[1000];
  char pattern[] = "^([^:]+):([^:]+)";
  if ((res = regcomp (&reg, pattern, REG_EXTENDED)) != 0)
    {
      regerror(res, &reg, buff, sizeof buff);
      fprintf (stderr, "regcomp: %s (%s)\n", buff, pattern);
      return 1;
    }
  if ((res = regexec (&reg, str, nmatch, rmatch, 0)) != 0)
    {
      regerror(res, &reg, buff, sizeof buff);
      fprintf (stderr, "%s (%s)\n", buff, pattern);
      return 1;
    }
  else {
    puts("match!");
    msize = rmatch[1].rm_eo - rmatch[1].rm_so;
    strncpy(mstr, str + rmatch[1].rm_so, msize);
    mstr[msize] = '\0';
    puts(mstr);
    msize = rmatch[2].rm_eo - rmatch[2].rm_so;
    strncpy(mstr, str + rmatch[2].rm_so, msize);
    mstr[msize] = '\0';
    puts(mstr);
  }
  return 0;
}
che poi:

Codice: Seleziona tutto

crap0101@orange:/tmp/FOO$ gcc -g -Wall -Wextra x.c 
crap0101@orange:/tmp/FOO$ ./a.out 'sdef: d wdw'
match!
sdef
 d wdw
crap0101@orange:/tmp/FOO$ ./a.out 's def: d wdw'
match!
s def
 d wdw
crap0101@orange:/tmp/FOO$ gcc -g -Wall -Wextra x.c 
crap0101@orange:/tmp/FOO$ ./a.out 'sdef:dwdw'
match!
sdef
dwdw
crap0101@orange:/tmp/FOO$ ./a.out 'sd ef:dwdw'
match!
sd ef
dwdw
crap0101@orange:/tmp/FOO$ ./a.out 'sd ef :dwdw'
match!
sd ef 
dwdw
crap0101@orange:/tmp/FOO$ ./a.out 'sd ef :dw dw'
match!
sd ef 
dw dw
crap0101@orange:/tmp/FOO$ ./a.out 'sd ef :   dw dw'
match!
sd ef 
   dw dw
http://www.gnu.org/ http://boinc.berkeley.edu/ http://www.python-it.org/
- Ricorda le ultime parole di suo padre: «Sta' alla larga dalle chiese, figlio. La sola cosa per cui hanno la chiave è il merdaio. E giurami che non porterai mai un distintivo della legge» - W.S. Burroughs
Scrivi risposta

Ritorna a “Programmazione”

Chi c’è in linea

Visualizzano questa sezione: 0 utenti iscritti e 4 ospiti