tags:

views:

76

answers:

3
+1  Q: 

C regex problem

Hi, all!
Q1.I want to match "&JOY" in a user input string, for example, "bla bla &JOY bla bla &JOY blabla" How can I write the regex expression for this, and are there any C regex functions could return all the positions where the matches happen?
Q2.If I want to substitute &JOY with another string is there a convenient C function to do this?

+2  A: 

It looks like your regular expression would not be very interesting. It would simply be:

&JOY

In other words, it looks like you are simply trying to match a literal sub-string. And if that is all you are doing, the I wouldn't bother with regex (like hitting a thumb tack with a sledge hammer).

Brent Arias
+3  A: 

C standard library does not provide regex functions. However, as your example looks for a fixed string, you don't need regex. Substring search is enough. It can be accomplished with strstr function:

#include <string.h>
..........

char* text = "bla bla &JOY bla bla &JOY blabla";
char* pattern = "&JOY";
char* substr_ptr;
int pos;

while ( substr_ptr = strstr(pattern, text) )
{
    pos = substr_ptr - text;
    printf("found at %d\n", pos);
}

As to your second question -- no, there is no such function. You have to do it manually:

  • if replacing string has the same length as the substring you want to replace, just overwrite it in-place (memcpy);
  • otherwise, you will have to allocate memory for resulting string and copy three parts there (original string before substring occurrence, replacing string, and the remainder of the original string).
atzz
A: 

R1. Could be "&JOY" or "(&JOY)" for get the substrings. Use regex.h to do it in C.

R2. If there will be other more advanced regex, use regex.h and implement your own function. It is very simple.

Tiago Natel
This is one of the worst answers I've read in a while
Falmarri
Really?? Why ??
Tiago Natel