I have lines from file like this:
{123} {12.3.2015 moday} {THIS IS A TEST}
is It possible to get every value between brackets {} and insert into array?
Also I wold like to know if there is some other solution for this problem...
to get like this:
array( 123,
'12.3.2015 moday',
'THIS IS A TEST'
)
My try:
int r;
regex_t reg;
regmatch_t match[2];
char *line = "{123} {12.3.2015 moday} {THIS IS A TEST}";
regcomp(®, "[{](.*?)*[}]", REG_ICASE | REG_EXTENDED);
r = regexec(®, line, 2, match, 0);
if (r == 0) {
printf("Match!\n");
printf("0: [%.*s]\n", match[0].rm_eo - match[0].rm_so, line + match[0].rm_so);
printf("1: %.*s\n", match[1].rm_eo - match[1].rm_so, line + match[1].rm_so);
} else {
printf("NO match!\n");
}
This will result:
123} {12.3.2015 moday} {THIS IS A TEST
Anyone know how to improve this?
To help you you can use the regex101 website which is really useful.
Then I suggest you to use this regex:
/(?<=\{).*?(?=\})/g
Or any of these ones:
/\{\K.*?(?=\})/g
/\{\K[^\}]+/g
/\{(.*?)\}/g
Also available here for the first one:
https://regex101.com/r/bB6sE8/1
In C you could start with this which is an example for here:
#include <stdio.h>
#include <string.h>
#include <regex.h>
int main ()
{
char * source = "{123} {12.3.2015 moday} {THIS IS A TEST}";
char * regexString = "{([^}]*)}";
size_t maxGroups = 10;
regex_t regexCompiled;
regmatch_t groupArray[10];
unsigned int m;
char * cursor;
if (regcomp(®exCompiled, regexString, REG_EXTENDED))
{
printf("Could not compile regular expression.\n");
return 1;
};
cursor = source;
while (!regexec(®exCompiled, cursor, 10, groupArray, 0))
{
unsigned int offset = 0;
if (groupArray[1].rm_so == -1)
break; // No more groups
offset = groupArray[1].rm_eo;
char cursorCopy[strlen(cursor) + 1];
strcpy(cursorCopy, cursor);
cursorCopy[groupArray[1].rm_eo] = 0;
printf("%s\n", cursorCopy + groupArray[1].rm_so);
cursor += offset;
}
regfree(®exCompiled);
return 0;
}
Related
so this is part of a kind of menu, the only problemis that the word is not getting into the array "frase" i have already tried with frase [ ] = "the word" but idk why it wont work
if(lvl==1)
{
printf("lvl 1\n");
if (opc==1)
{
printf("Animales\n");
a = rand() %3 + 1;
printf("%d", a);
if (a=1)
frase <= "pato";
if (a=2)
frase <="ganso";
if (a=3)
frase <= "avispa";
}
if (opc==2)
{
printf("comida\n");
a = rand() %3 + 1;
if (a=1)
frase <="pasta";
if (a=2)
frase <="pizza";
if (a=3)
frase <="pastel";
}
if (opc==3)
{
printf("paises\n");
a = rand() %3 + 1;
if (a=1)
frase <="peru";
if (a=2)
frase <="brasil";
if (a=3)
frase <="egipto";
}
}
`
I suggest you solve this by modeling your data. In this case with a array of structs. Then you index into to obtain the relevant data:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main() {
struct {
const char *opc;
const char **frase;
} data[] = {
{"Animales", (const char *[]) { "pato", "ganso", "avispa" }},
{"comida", (const char *[]) { "pasta", "pizza", "pastel" }},
{"paises", (const char *[]) { "peru", "brasil", "egipto" }}
};
srand(time(0));
int opc = rand() % 3;
printf("lvl 1 %s %s\n", data[opc].opc, data[opc].frase[rand() % 3]);
return 0;
}
If you have a lot of data put the data in a file and write a function to build the struct at start-up. A special case of this approach is to store the data in a lightweight database like SQLite, then you can query for the relevant data at run-time or load it all it upon start-up.
You many no longer need to copy the frase, but if you want to use a strcpy:
char frase[100];
strcpy(frase, data[opc].frase[rand() % 3]);
Multiple things to be improved in the code. The if(a=1) should be changed to ==. Not sure what you mean by frase<="pato", strcpy or strncpy should be used. Please refer the following sample code.
void copytoarray(char *array, char *word, unsigned int len)
{
if(array == NULL || word == NULL)
{
return;
}
strncpy(array, word, len);
}
int main(void) {
char frase[15] = {'\0'};
int a, lvl =1;
int opc =1;
if(lvl==1)
{
printf("lvl 1\n");
if (opc==1)
{
printf("Animales\n");
a = rand() %3 + 1;
printf("%d\n", a);
if (a==1)
copytoarray(frase, "pato", strlen("pato"));
if (a==2)
copytoarray(frase, "ganso", strlen("ganso"));
if (a==3)
copytoarray(frase, "avispa", strlen("avispa"));
}
}
printf("Word: %s\n ",frase);
}
So, I am trying to check the format of a key using the regex.h library in C. This is my code:
#include <stdio.h>
#include <regex.h>
int match(char *reg, char *string)
{
regex_t regex;
int res;
res = regcomp(®ex, reg, 0);
if (res)
{
fprintf(stderr, "Could not compile regex\n");
return 1;
}
res = regexec(®ex, string, 0, NULL, 0);
return res;
}
int main(void)
{
char *regex = "[\\w-]{24}\\.[\\w-]{6}\\.[\\w-]{27}|mfa\\.[\\w-]{84}";
char *key = "xxxxxxxxxxxxxxxxxxxxxxxx.xxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxx";
if (match(regex, key) == 0) printf("Valid key!\n");
else printf("Invalid key!\n");
return 0;
}
When I run this code, I get the output:
Invalid key!
Why is this happening? If I try to test the same key with the same regex in Node.JS, I get that the key does match the regex:
> const regex = new RegExp("[\\w-]{24}\\.[\\w-]{6}\\.[\\w-]{27}|mfa\\.[\\w-]{84}");
undefined
> const key = "xxxxxxxxxxxxxxxxxxxxxxxx.xxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxx";
undefined
> regex.test(key)
true
How could I get the right result using C?
Thanks in advance,
Robin
There are at least two issues here and one extra potential problem:
The limiting quantifiers will work as such in a POSIX ERE flavor, thus, as it has been pointed out in comments, you need to regcomp the pattern with a REG_EXTENDED option (i.e. res = regcomp(®ex, reg, REG_EXTENDED))
The \w shorthand character class does not work inside bracket expressions as a word char matching pattern, you need to replace it with [:alnum:]_, i.e. [\w-] must be replaced with [[:alnum:]_-]. The solution will be:
char *regex = "[[:alnum:]_-]{24}\\.[[:alnum:]_-]{6}\\.[[:alnum:]_-]{27}|mfa\\.[[:alnum:]_-]{84}";
Besides, if your regex must match the two alternatives exactly, you need to use a group around the whole pattern and add ^ and $ anchors on both ends. The solution will be:
char *regex = "^([[:alnum:]_-]{24}\\.[[:alnum:]_-]{6}\\.[[:alnum:]_-]{27}|mfa\\.[[:alnum:]_-]{84})$";
See this C demo:
#include <stdio.h>
#include <regex.h>
int match(char *reg, char *string)
{
regex_t regex;
int res;
res = regcomp(®ex, reg, REG_EXTENDED);
if (res)
{
fprintf(stderr, "Could not compile regex\n");
return 1;
}
res = regexec(®ex, string, 0, NULL, 0);
return res;
}
int main(void)
{
char *regex = "^([[:alnum:]_-]{24}\\.[[:alnum:]_-]{6}\\.[[:alnum:]_-]{27}|mfa\\.[[:alnum:]_-]{84})$";
char *key = "xxxxxxxxxxxxxxxxxxxxxxxx.xxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxx";
if (match(regex, key) == 0) printf("Valid key!\n");
else printf("Invalid key!\n");
return 0;
}
// => Valid key!
I need to verify a String(string:89dree01) with regular expression ([a-zA-Z0-9]*) using if condition in C like so:
if(string=regex) {}
Could someone help me with this?
Below is the code snippet:
#include <regex.h>
#include <stdio.h>
int main()
{
regex_t * regex = "[a-zA-Z0-9]*";
int value;
value = regcomp(regex,"89dree01", 0);
if (value == 0) {
LOG("RegEx compiled successfully.");
}
else {
LOG("Compilation error.");
}
return 0;
}
You're not using the POSIX regexp library quite correctly.
Here's an example that checks whether arguments given on the command line match that regexp (slightly modified).
#include <regex.h>
#include <stdio.h>
int main(int argc, char **argv) {
regex_t regex;
if (regcomp(®ex, "^[a-zA-Z0-9]+$", REG_NOSUB | REG_EXTENDED)) {
return 1;
}
for (int i = 1; i < argc; i++) {
int status = regexec(®ex, argv[i], 0, NULL, 0);
printf("%s: %s\n", argv[i], status == REG_NOMATCH ? "no match" : "matched");
}
return 0;
}
~/Desktop $ gcc -o s s.c
~/Desktop $ ./s aaa bb0 00a11 ..--
aaa: matched
bb0: matched
00a11: matched
..--: no match
Edit:
Simply (if inefficiently) put, you can wrap this in a function:
int does_regexp_match(const char *string, const char *regexp) {
regex_t r;
if (regcomp(&r, regexp, REG_NOSUB | REG_EXTENDED)) {
return -1;
}
return regexec(&r, string, 0, NULL, 0) == 0 ? 1 : 0;
}
if(does_regexp_match("89dree01", "^[a-zA-Z0-9]+$") == 1) {
// it's a match
}
I wanted to improve my C skills, so I search some program's ideas.
Someone propose to create a simple Brainf*** interpreter and then a compiler. So here I am.
I created the interpreter and it works as expected, except with the Mandelbrot program:
A mandelbrot set fractal viewer in brainfuck written by Erik Bosman
+++++++++++++[->++>>>+++++>++>+<<<<<<]>>>>>++++++>--->>>>>>>>>>+++++++++++++++[[
>>>>>>>>>]+[<<<<<<<<<]>>>>>>>>>-]+[>>>>>>>>[-]>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>[-]+
<<<<<<<+++++[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>>>+>>>>>>>>>>>>>>>>>>>>>>>>>>
>+<<<<<<<<<<<<<<<<<[<<<<<<<<<]>>>[-]+[>>>>>>[>>>>>>>[-]>>]<<<<<<<<<[<<<<<<<<<]>>
>>>>>[-]+<<<<<<++++[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>>+<<<<<<+++++++[-[->>>
>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>>+<<<<<<<<<<<<<<<<[<<<<<<<<<]>>>[[-]>>>>>>[>>>>>
>>[-<<<<<<+>>>>>>]<<<<<<[->>>>>>+<<+<<<+<]>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>
[>>>>>>>>[-<<<<<<<+>>>>>>>]<<<<<<<[->>>>>>>+<<+<<<+<<]>>>>>>>>]<<<<<<<<<[<<<<<<<
<<]>>>>>>>[-<<<<<<<+>>>>>>>]<<<<<<<[->>>>>>>+<<+<<<<<]>>>>>>>>>+++++++++++++++[[
>>>>>>>>>]+>[-]>[-]>[-]>[-]>[-]>[-]>[-]>[-]>[-]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>-]+[
>+>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>[>->>>>[-<<<<+>>>>]<<<<[->>>>+<<<<<[->>[
-<<+>>]<<[->>+>>+<<<<]+>>>>>>>>>]<<<<<<<<[<<<<<<<<<]]>>>>>>>>>[>>>>>>>>>]<<<<<<<
<<[>[->>>>>>>>>+<<<<<<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>>>>>-<<<<<<[<<<<
<<<<<]]>>>]
I don't understand why, but my program keeps getting stuck in some sort of endless loop. I try to debug it using gdb but it's hard to find the right breakpoint in order to see why it stuck.
The program is as follows:
#include <stdio.h>
#include <stdlib.h>
// Brainfuck instructions
// > Math stuff
#define INCR '+' // +1 on current MS
#define DECR '-' // -1 on current MS
// > Memory slot stuff
#define FORW '>' // Go to next MS
#define BACK '<' // Go to previous MS
// > Logic stuff
#define SJMP '[' // Loop till current MS value is equal to zero
#define EJMP ']' // Jump to the beginning of the loop
// > I/O stuff
#define PRTC '.' // Print character with MS value as ASCII code
#define GETC ',' // Get an user input ASCII character code
typedef unsigned char byte;
// The brainfuck program struct
typedef struct {
byte *values;
int size;
int index;
byte *loops_starts;
int loop_size;
int loop_index;
} BrainfuckProgram;
void initialize(BrainfuckProgram *bfp) {
bfp->values = malloc(bfp->size * sizeof(*bfp->values));
bfp->loops_starts = malloc(bfp->size * sizeof(*bfp->loops_starts));
}
int allocate_values(BrainfuckProgram *bfp) {
byte *newMem = realloc(bfp->values, bfp->size * sizeof(byte));
if (!newMem) {
return 1;
}
bfp->values = newMem;
return 0;
}
int allocate_new_loop(BrainfuckProgram *bfp) {
byte *newMem = realloc(bfp->loops_starts, bfp->loop_size * sizeof(byte));
if (!newMem) {
return 1;
}
bfp->loops_starts = newMem;
return 0;
}
void set_value(BrainfuckProgram *bfp, byte value) {
int tempValue = value < 0 ? 255: value % 256;
*(bfp->values + bfp->index) = tempValue;
}
int get_value(BrainfuckProgram *bfp) {
return *(bfp->values + bfp->index);
}
// FILE functions
int get_file_name(int argc, char *argv[], char** fname) {
if (argc == 1) {
printf("File name is missing\n");
return 1;
}
*fname = argv[1];
return 0;
}
int get_file_size(FILE *file) {
fseek(file, 0L, SEEK_END);
int size = ftell(file);
rewind(file);
return size;
}
// Main function
int main(int argc, char *argv[]) {
// Vector part
BrainfuckProgram bfp = {
.values = NULL,
.size = 1,
.index = 0,
.loops_starts = NULL,
.loop_index = 0,
.loop_size = 0
};
initialize(&bfp);
// FILE Part
char* fname = NULL;
int error = get_file_name(argc, argv, &fname);
if (error) {
goto exit;
}
// Create file variable
FILE *fin = NULL;
fin = fopen(fname, "r");
int size = get_file_size(fin);
// Create a char array of the right size
byte *prog = NULL;
prog = malloc(size * sizeof(*prog));
// Read 1 byte size times
fread(prog, 1, size, fin);
for (int i = 0; i < size; i++) {
byte current = *(prog+i);
switch (current) {
case INCR:
set_value(&bfp, get_value(&bfp) + 1);
break;
case DECR:
set_value(&bfp, get_value(&bfp) - 1);
break;
case FORW:
// if index+1 == size then we are at the
// last element of the vector cause
// size = index - 1
if (bfp.index+1 == bfp.size) {
bfp.size++;
int error = allocate_values(&bfp);
if (error) {
printf("an error occured while forwarding pointer");
goto close;
}
}
bfp.index++;
break;
case BACK:
// bfp.index == 0 then !bfp.index == true
if (!bfp.index) {
printf("can go back from index 0\n");
goto close;
}
bfp.index--;
break;
case SJMP:
if (bfp.loop_index == bfp.size) {
bfp.loop_size++;
int error = allocate_new_loop(&bfp);
if (error) {
printf("an error occured while forwarding pointer");
goto close;
}
}
bfp.loop_index++;
*(bfp.loops_starts + bfp.loop_index) = i;
break;
case EJMP:
if (bfp.loop_index == -1) {
printf("cannot go back");
goto close;
}
if (get_value(&bfp) != 0) {
i = *(bfp.loops_starts + bfp.loop_index);
} else {
bfp.loop_index--;
}
break;
case PRTC:
printf("%c", get_value(&bfp));
break;
case GETC:
; // Semicolon here because of the label error
byte buf;
scanf("%c", &buf);
set_value(&bfp, buf);
break;
}
}
close:
fclose(fin);
exit:
;
return 0;
}
I'd like to have some C related advice on what I have done wrong too.
The Mandelbrot program takes a decent time to run on a good interpreter. Yours, well, it isn't that good. That's why it "hangs" at the start.
Some good ideas that you had, performance-wise:
precalculating loops
Some bad ideas, performance-wise:
Using abstracted allocation functions instead of calling realloc
using scanf and printf instead of getchar and putchar
Some odd things that you did:
Manually truncating an unsigned char when wraparound is implicit
checking if an unsigned char is less than 0
using *(x + y) syntax instead of array indexing x[y]
I don't think you actually use those precalculated loops, if you do then probably not correctly
You also probably create a new precalculated loop every time you go over the loop again
Using the get_value and set_value functions instead of pointers (this will be a performance issue if you don't compile with optimizations)
A couple suggestions:
Try to avoid calling functions when you don't need to as much as possible.
Write a BrainFuck->C compiler using this reference.
On second thought, maybe you should try to debug this program instead.
You may also use my interpreter as a reference if you're OK with GPLv3. Note that it doesn't precalculate loops.
Am in my way to practice how to use the pcre regex library, to match regular expression/pattern against a given data/buffer.Then if there is match, i have to load the matched string to may array/list. but, when i print my list/array (using a for loop), the output is unexpected/wrong. pls see how the logic works:
1.first i have to load patterns/regex.....i have a function to do this and returns patterns in an array/list.
2.iterate on each pattern and search for match in a data/buffer....pcre library handles this business.
3.if match exists, push/fill to a list/array
4.print out all matches with in loop
my sample code is:
code.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pcre.h>
#define NUMBER 3
#define MAX_GROUPS 200
char *data = "Jun 12 05 12:24:48 100.101.102.103 end";
char **load_patern()
{
char **regex_array = malloc (sizeof (char *) * NUMBER);
regex_array[0] = "(\\w+\\s\\d+\\s\\d+\\s\\d+:\\d+:\\d+)"; //pattern to match date time
regex_array[1] = "(\\d+.\\d+.\\d+.\\d+)"; //pattern for ip_adress
regex_array[2] = "(end)";//pattern for "end"
return regex_array;
}
int main()
{
char **patern_list = load_patern();
int t,i,size,rc,p,re_err_offset,re_vce[MAX_GROUPS];
char sBuffer[512];
char *pLasts = NULL;
pcre *re_compiled;
pcre_extra *re_extra;
const char *re_err_str;
char *token,*logg,*next,*match_str;
char **struct_list = malloc (sizeof (char *) * NUMBER);
for(t=0;t<3;t++) //3 is number of patterns, patern_list size
{
snprintf(sBuffer, sizeof(sBuffer), "%s",data);
pLasts = sBuffer;
re_compiled = pcre_compile(patern_list[t], 0, &re_err_str,
&re_err_offset, NULL);
re_extra = pcre_study(re_compiled, 0, &re_err_str);
next = pLasts;
size = strlen(pLasts);
rc = pcre_exec(re_compiled, re_extra, next, size, 0, 0, re_vce, MAX_GROUPS);
if(rc>0) //if match exists
{
next[re_vce[3]] = '\0';
match_str = next + re_vce[2];
struct_list[t] = match_str;
printf("data at [%d]:%s\n",t,struct_list[t]);//this prints correctly
}
}
//but,here am trying to print each match stored in struct_list[], but it fails to display correctly.
for(p=0; p<3; p++)
{
printf("loop_one: [%d]----%s\n",p,struct_list[p]);
}
return 0;
}
The out put from a loop iterating on p,should be:
loop_one: 0----Jun 12 05 12:24:48
loop_one: 1----100.101.102.103
loop_one: 2----end
any thing i miss?