Home > Back-end >  Consult with C language using regex library regular screening of consecutive Numbers/letters
Consult with C language using regex library regular screening of consecutive Numbers/letters

Time:12-20

Development environment: VS2017
Using regex library 2.7, should be the latest,

The regex function prototype
Int regexec (const regex_t * preg, const char * string, size_t nmatch, regmatch_t pmatch [], int eflags);

In the process of matching strings, with regular looking for continuous Numbers, now two problems:
1. For "we12312332qwwww d1246Xdes" this string, I use "\ [0-9] {4}" match four Numbers in a row, but each time the regex matches only the first "1231" is returned, the subsequent "2332" "1246" can't match, I fill in pmatch array parameter support up to 25 matches, but in addition to the first has the corresponding information of characters, the others are all - 1. If I remove the first 1231, can match again for the next 2332.
2. There is a question that if I match the "1234" for two consecutive Numbers in the series, is there a way to match the "12", "23", "34" such results? Because I now want to be a dirty data processing may want to consider this,
The above two questions, hope your bosses teach

 
# include & lt; Stdio. H>
# include & lt; String. H>
# include "regex. H"

Int main (int arg c, char * argv [])
{
int len;
Regex_t re;
Regmatch_t subs [25];
Char matched [1024].
Char errbuf [128].
Int err=0, I=0;
Char SRC [1024]={" we12312332qwwww d1246Xdes "};
Char pattern [1024]={" \ [0-9] {4} "};


/* compile the regular expression */
Err=regcomp (& amp; Re, the pattern, REG_EXTENDED);

If (err)
{
Len=regerror (err, & amp; Re, errbuf, sizeof (errbuf));
Printf (" error: regcomp: % s \ r \ n ", errbuf);
return 1;
}
Printf (" Total from the subexpression: % d \ n ", re. Re_nsub);
Performing pattern matching/* */
Err=regexec (& amp; Re, SRC, 25, subs, 0);
If (err==REG_NOMATCH)
{
Printf (" no match... \r\n");
Regfree (& amp; Re);
return 0;
}
Else if (err)
{
Len=regerror (err, & amp; Re, errbuf, sizeof (errbuf));
Printf (" error: regexec: % s \ r \ n ", errbuf);
return 1;
}

Printf (" OK, has matched... \r\n");
for (i=0; I & lt;=re. Re_nsub; I++)
{
Len=subs [I] rm_eo - subs [I] rm_so;
If (0==I)
{
Printf (" the begin: % d, len=% d \ r \ n ", subs [I] rm_so, len);
}
The else
{
Printf (" begin subexpression % d: % d, len=% d ", I, subs [I] rm_so, len);
}
Memcpy (matched, SRC + subs [I] rm_so, len);
Matched [len]='\ 0';
Match: printf (" % s \ n ", matched);
}

Regfree (& amp; Re);
return 0;

}


  • Related