jim ying
jim ying

Reputation: 391

convert javascript regex to posix regix

javascript regex:

reg = /\/\*[\s\S]*?\*\//

I use it to remove code comments like "/* xxxx */", which work fine.

Now I want to convert to posix extended regex use c language,

// use regex.h
// regcomp
const char *patten = "TODO";  // need convert from javascript regex
regcomp(&re, patten,REG_EXTENDED);

I try as follow:

const char *patten = "\\/\\*[[:space:]^[:space:]]*?\\*\\/";
/*
* javascript regex white space \s convert to posix [:space:]
*/

but it not work. where is wrong?

Upvotes: 3

Views: 395

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626893

You can write it as

const char *patten = "/\\*[^*]*\\*+([^/*][^*]*\\*+)*/";

Details:

  • /\* - starting /* char sequence
  • [^*]* - zero or more characters other than *
  • \*+ - one or more literal *
  • ([^/*][^*]*\*+)* - zero or more sequences of:
    • [^/*] - a char other than a / and *
    • [^*]* - zero or more chars other than asterisk
    • \*+ - one or more asterisks
  • / - a closing / char.

See the regex demo.

Upvotes: 2

Related Questions