hari
hari

Reputation: 9733

regex not working

This is the string I want to match

str = "hello_my_world";

         regex_t reg;
         if (regcomp(&reg, pattern, REG_EXTENDED | REG_ICASE) != 0) {
             exit (-1);
         }

         if (regexec(&reg, str, 0, NULL, 0) != 0) {
             regfree(&reg);
             /* did not match */
         }

         regfree(&reg);
     }

if pattern is hello_* it returns true. but if pattern is hello_*_world it doesn't...is that expected?

how can I match it?

Upvotes: 0

Views: 112

Answers (3)

hmakholm left over Monica
hmakholm left over Monica

Reputation: 23332

You need to read up on regex syntax. The pattern hello_*_world will match "hello", followed by zero or more underscores, followed by yet an underscore, followed by "world".

What you want for a pattern is hello_.*_world, which maches "hello_" followed by zero or more arbitrary chraracters, followed by "_world".

The pattern hello_* matches, because your string contains a "hello" that is followed by zero or more underscores.

Upvotes: 5

Rudy Velthuis
Rudy Velthuis

Reputation: 28806

Try a pattern of hello_.+_world or hello_[A-Za-z]+_world.

The * applies to the char before it (0 or more occurrences), so it matches hello_world, hello__world, hello___world, etc.

Upvotes: 1

Owen
Owen

Reputation: 39356

Regex * is different from glob *: it means "0 or more of the previous atom"

So I think you want:

hello_.*_world

Upvotes: 2

Related Questions