Link to home
Start Free TrialLog in
Avatar of tcy08
tcy08

asked on

Regular Expression in C ???

char *str1 = "abc & def";
char *str2 = "this's";

How do I do regular expression on above str1 and str2, so it will replace & with @, and ' with ` ???
Avatar of newmang
newmang

C itself doesn't have regular expressions, why don't you just code it.

Example 1 - where single character is to be replaced with another single character....

int replace(char * str1,char old_char, char new_char)
{
char * ptr_temp;
char * ptr_in;
char * ptr_out;

    if((ptr_temp=(char *)malloc(strlen(str1)+1))==NULL)
        return 1;
    ptr_in=str1;
    ptr_out=str2;
    while(*ptr_in!=0x00)
    {
        if(*ptr_in==old_char)
        {
            *ptr_out=new_char;
            ptr_in++;
            ptr_out++;
            continue;
        }
        *ptr_out++=*ptr_in++;
     }
     *ptr_out=0x00;
     strcpy(str1,ptr_temp);
     free(ptr_temp);
     return 0;
}

Example 2 - replacing a character with a string...

int replace(char * str2,char old_char, char * new_str)
{
// This function assumes that str2 is big enough to accomodate the new string!
char * ptr_temp;
char * ptr_in;
char * ptr_out;
int    n_chars_to_replace=0;
int    len_temp;
int    len_new_str;

    // Find out how many characters need to be replaced.
    ptr_in=str2;
    while(*ptr_in!=0x00)
    {
         if(*(ptr_in++)==old_char)
             n_chars_to_replace++;
    }
    if(n_chars_to_replace==0)
         return 0;
    len_new_str=strlen(new_str);
    len=strlen(str2)+1+(n_chars_to_replace*(len_new_str-1));
    if((ptr_temp=(char *)malloc(len))==NULL)
        return 1;
    memset(ptr_temp,0x00,len);
    ptr_in=str1;
    ptr_out=str2;
    while(*ptr_in!=0x00)
    {
        if(*ptr_in==old_char)
        {
            strcat(ptr_out,new_str);
            ptr_in++;
            ptr_out+=len_new_str;
            continue;
        }
        *ptr_out++=*ptr_in++;
     }
     *ptr_out=0x00;
     strcpy(str2,ptr_temp);
     free(ptr_temp);
     return 0;
}
newmang:


In Example 1 - You mean ptr_out = ptr_temp; right? Not ptr_out=str2;

By the way what is 0x00 in the while loop and other places?
thanks, sammani.
sammani

You are right re ptr_out, sorry, metal slip of the tongue. The 0x00 is the NULL character used by C to signify the end of a string.

By the way, on reflection example 1 can be made much simpler. Because you are replacing a single character with another single character it is possible to make the change in place in the original string without making a temp string. The code would be as follows...

void replace(char * str1, char old_char, char new_char)
{
char *ptr;

    ptr-str1;
    while(*ptr!=0x00) // Test each char till we hit the trailing NULL.
    {
        if(*ptr==old_char)
            *ptr=new_char;
        ptr++;
    }
    return;
}

Cheers - Gavin
If you are familiar with strtok or strchr to split the strings on the chars that you want to remove (& and ' respectively) and then, simply substitute the chars which you want.

That way, you can leave the complexity of the searching with built in library functions. Also, this will be more optimized.

WR,
Joy
strtok & strchr is a bit of overkill in the first case where he wants to replace a single character with another, I agree you could use strchr with a moving base pointer for the strchr but my code essentially does what that would do anyway.

Using strtok & strchr in the second case where he wants to replace a single character with a string would introduce the complexity of allocating space to store the substrings created by the strtok operation.

I agree that these functions could be used to do the job, its the beauty of C in that there are many ways to denude a feline, each of which has its good & bad points. My method is simple and shows him what is happening, I have used this method often and I don't notice and performance degradation, I dissasembled the binary generated by my compiler(s) after optimisation to see if I could get any speed improvement with embedded asm code but it looks pretty tight to me.
Joy

Please don't post proposed answers unless you know that yours is the correct solution as it locks the question for others comments.

This question was LOCKED with a PROPOSED ANSWER and awaits your decision today.  Once a question is LOCKED with a Proposed Answer, few new experts will step in to help on that question, since the assumption is, you've been helped.  If the Proposed Answer helped you, please accept it and award that expert.  If it did not help you, please reject it and add comments as to status and what else is needed.
 
If you wish to award multiple experts, just comment here with detail, I'll respond as soon as possible.  As it stands today, you asked the question, got help and not one expert was awarded for the contribution(s) made.  Your response is needed.  I'll monitor through month end, and if you've not returned to complete this, we'll need to decide.  Expert input is welcome (as always) to determine the outcome here if the Asker does not respond.
 
Your response in finalizing this (and ALL) your question(s) is appreciated.
 
Moondancer
Community Support Moderator @ Experts Exchange

ASKER CERTIFIED SOLUTION
Avatar of Triskelion
Triskelion
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ADMINISTRATION WILL BE CONTACTING YOU SHORTLY.  Moderators Computer101 or Netminder will return to finalize these if still open in seven days.  Please post closing recommendations before that time.

Question(s) below appears to have been abandoned. Your options are:
 
1. Accept a Comment As Answer (use the button next to the Expert's name).
2. Close the question if the information was not useful to you, but may help others. You must tell the participants why you wish to do this, and allow for Expert response.  This choice will include a refund to you, and will move this question to our PAQ (Previously Asked Question) database.  If you found information outside this question thread, please add it.
3. Ask Community Support to help split points between participating experts, or just comment here with details and we'll respond with the process.
4. Delete the question (if it has no potential value for others).
   --> Post comments for expert of your intention to delete and why
   --> YOU CANNOT DELETE A QUESTION with comments; special handling by a Moderator is required.

For special handling needs, please post a zero point question in the link below and include the URL (question QID/link) that it regards with details.
https://www.experts-exchange.com/jsp/qList.jsp?ta=commspt
 
Please click this link for Help Desk, Guidelines/Member Agreement and the Question/Answer process.  https://www.experts-exchange.com/jsp/cmtyHelpDesk.jsp

Click you Member Profile to view your question history and please keep them updated. If you are a KnowledgePro user, use the Power Search option to find them.  

Questions which are LOCKED with a Proposed Answer but do not help you, should be rejected with comments added.  When you grade the question less than an A, please comment as to why.  This helps all involved, as well as others who may access this item in the future.  PLEASE DO NOT AWARD POINTS TO ME.

To view your open questions, please click the following link(s) and keep them all current with updates.
https://www.experts-exchange.com/questions/Q.20020256.html
https://www.experts-exchange.com/questions/Q.20275491.html
https://www.experts-exchange.com/questions/Q.20278358.html
https://www.experts-exchange.com/questions/Q.20278843.html
https://www.experts-exchange.com/questions/Q.20288064.html
https://www.experts-exchange.com/questions/Q.20288080.html
https://www.experts-exchange.com/questions/Q.20288780.html
https://www.experts-exchange.com/questions/Q.20288783.html
https://www.experts-exchange.com/questions/Q.20288785.html
https://www.experts-exchange.com/questions/Q.20289261.html
https://www.experts-exchange.com/questions/Q.20289866.html
https://www.experts-exchange.com/questions/Q.20290728.html
https://www.experts-exchange.com/questions/Q.20287467.html


To view your locked questions, please click the following link(s) and evaluate the proposed answer.
https://www.experts-exchange.com/questions/Q.20030535.html
https://www.experts-exchange.com/questions/Q.20024123.html
https://www.experts-exchange.com/questions/Q.20022811.html

*****  E X P E R T S    P L E A S E  ******  Leave your closing recommendations if this item remains inactive another seven (7) days.  If you are interested in the cleanup effort, please click this link https://www.experts-exchange.com/jsp/qManageQuestion.jsp?ta=commspt&qid=20274643 
POINTS FOR EXPERTS awaiting comments are listed here -> https://www.experts-exchange.com/commspt/Q.20277028.html
 
Moderators will finalize this question if in @7 days Asker has not responded.  This will be moved to the PAQ (Previously Asked Questions) at zero points, deleted or awarded.
 
Thank you everyone.
 
Moondancer
Moderator @ Experts Exchange
Zero response, so finalized today.
Moondancer - EE Moderator