Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
C Regex multiple matches and groups example
# gcc -Wall -o match match.c && ./match
#
#include <stdio.h>
#include <string.h>
#include <regex.h>
int main ()
{
char * source = "___ abc123def ___ ghi456 ___";
char * regexString = "[a-z]*([0-9]+)([a-z]*)";
size_t maxMatches = 2;
size_t maxGroups = 3;
regex_t regexCompiled;
regmatch_t groupArray[maxGroups];
unsigned int m;
char * cursor;
if (regcomp(&regexCompiled, regexString, REG_EXTENDED))
{
printf("Could not compile regular expression.\n");
return 1;
};
m = 0;
cursor = source;
for (m = 0; m < maxMatches; m ++)
{
if (regexec(&regexCompiled, cursor, maxGroups, groupArray, 0))
break; // No more matches
unsigned int g = 0;
unsigned int offset = 0;
for (g = 0; g < maxGroups; g++)
{
if (groupArray[g].rm_so == (size_t)-1)
break; // No more groups
if (g == 0)
offset = groupArray[g].rm_eo;
char cursorCopy[strlen(cursor) + 1];
strcpy(cursorCopy, cursor);
cursorCopy[groupArray[g].rm_eo] = 0;
printf("Match %u, Group %u: [%2u-%2u]: %s\n",
m, g, groupArray[g].rm_so, groupArray[g].rm_eo,
cursorCopy + groupArray[g].rm_so);
}
cursor += offset;
}
regfree(&regexCompiled);
return 0;
}
@sachinites

This comment has been minimized.

Copy link

@sachinites sachinites commented Aug 6, 2017

great example ...

@bandblad

This comment has been minimized.

Copy link

@bandblad bandblad commented Nov 22, 2018

Fucking finally. Someone posted multiple matches case.

@ShahFaisalIslam

This comment has been minimized.

Copy link

@ShahFaisalIslam ShahFaisalIslam commented Oct 18, 2019

Much needed code. Thank you a million times for this!

@raoulduke

This comment has been minimized.

Copy link

@raoulduke raoulduke commented Mar 6, 2020

Great example, it's hard to find one that captures multiple matches. I had to write my own the other day and this would have helped. Here's my similar Gist in case it helps anyone else out.

@weiT1993

This comment has been minimized.

Copy link

@weiT1993 weiT1993 commented Mar 17, 2020

This is extremely helpful for me. Thank you so much!

@firezdog

This comment has been minimized.

Copy link

@firezdog firezdog commented May 26, 2020

Why do you get the offset from the first group rather than the last?

@cb7754

This comment has been minimized.

Copy link

@cb7754 cb7754 commented Feb 9, 2021

Excellent example. Everything you need to use regex

@d1y

This comment has been minimized.

Copy link

@d1y d1y commented Apr 18, 2021

Thank you!!! I Just need the example code

@zhangxy0517

This comment has been minimized.

Copy link

@zhangxy0517 zhangxy0517 commented Apr 26, 2021

Thanks for the example.

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