PDA

View Full Version : Extended Regular Expression (regcomp() e regexec())


felix
05-13-2004, 03:02 PM
Hi,

I'm studing the regcomp() & regexec(), so i done this basic code (based at man help):

#include <stdio.h>
#include <regex.h>

int main (int argc, char *argv[]){

char string[]="A StRanGE phrase TO test tHiS ugly cOde";
int x;

x = match(string, argv[1]);

if ( x == 1 ){

printf("\n\n Mismatch \n\n");
}

return(0);
}

match(const char *string, char *pattern){

int status;
regex_t re;

if (regcomp(&re, pattern, REG_EXTENDED | REG_ICASE | REG_NOSUB) != 0) {

return(0); /* Report error. */

}

status = regexec(&re, string, (size_t) 0, NULL, 0);

regfree(&re);

if (status != 0) {

return(0); /* Report error. */

}

return(1);

}

So, it appear to work, i put the phrase at string[] to test the case sensitive of regcomp() and regexec() too! ;-)

Well, i want to elaborete a expression that allow me only mismatch if i pass a value that have the "strange" AND "ugly" strings at the some buffer (string([]).

If i test one peer time it work:

# ./x strange


Mismatch

# ./x ugly


Mismatch

If i test something that doesn't exist:

# ./x fakestring
#

What make me means that all is working ;-)

But when i try do mixed searches like i exposed above it doesn't work (i think that i'm making bad ERE, as i don't understand it very well), i tryed:

Not work...

# ./x strange+ugly

Not work...

# ./x strange*ugly

Not work...

# ./x "(strange)+(ugly)"

Not work...

# ./x "(strange)*(ugly)"


Mismatch

Now, it APPEAR to work, but it if i change the first string by fake it yet work, so it's wrong.. :/

# ./x "(fake)*(ugly)"


Mismatch

:(

How to make this ERE in a correct way ?

Thkz.

Regards

i3839
05-13-2004, 08:46 PM
* means zero or more of the previous characters (or whatever), so I think you want something like (notice the '.'):
# ./x "strange.*ugly"

felix
05-13-2004, 09:46 PM
Hi i3839,

Thkz a lot, it worked!

ps.: How i'm wired :P

Well, let's use this topic, someone know a funcion or if exist some way of make the something that with regexec() but instead of return if it's found or not as the above example replace the strings. For example if it find strange AND ugly so replace it by normal and wonderful ? ;)

Regards..

i3839
05-13-2004, 10:06 PM
You could take a look at the source code of sed...

felix
05-14-2004, 03:43 PM
Hummm, good idea, thkz again. ;)

regards

Kapil
05-31-2007, 07:30 PM
Hi Felix,
Incase you have any doubts, you can ask , I would be more than happy to help.

-Kapil