开发者

C regex to get position of a string and substitute another

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 funct开发者_StackOverflow社区ions 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?


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).


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).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜