0

我需要在 C 中替换字符串。在此处的答案之一中推荐了如何在纯 C 中进行正则表达式字符串替换?使用 PCRS 库。我从这里ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/Contrib/下载了 PCRS,但我对如何使用它感到困惑。下面是我的代码(取自另一个 SE 帖子)

            const char *error;
            int   erroffset;
            pcre *re;
            int   rc;
            int   i;
            int   ovector[100];

            char *regex = "From:([^@]+).*";
            char str[]  = "From:regular.expressions@example.com\r\n";
            char stringToBeSubstituted[] = "gmail.com";

            re = pcre_compile (regex,          /* the pattern */
                               PCRE_MULTILINE,
                               &error,         /* for error message */
                               &erroffset,     /* for error offset */
                               0);             /* use default character tables */
            if (!re)
            {
                printf("pcre_compile failed (offset: %d), %s\n", erroffset, error);
                return -1;
            }

            unsigned int offset = 0;
            unsigned int len = strlen(str);
            while (offset < len && (rc = pcre_exec(re, 0, str, len, offset, 0, ovector, sizeof(ovector))) >= 0)
            {
                for(int i = 0; i < rc; ++i)
                {
                    printf("%2d: %.*s\n", i, ovector[2*i+1] - ovector[2*i], str + ovector[2*i]);
                }
                offset = ovector[1];
            }

与“pcre_compile”和“pcre_exec”相反,我需要从 PCRS 使用哪些功能?

谢谢。

4

1 回答 1

0

只需按照INSTALL文件中的说明进行操作:

要构建 PCRS,您需要 pcre 3.0 或更高版本以及 gcc。

安装很简单: ./configure && make && make install 调试模式可以通过 --enable-debug 来启用。

包含一个简单的演示应用程序(pcrsed)。

PCRS 提供了手册页中记录的以下功能pcrs.3

  • pcrs_compile
  • pcrs_compile_command
  • pcrs_execute
  • pcrs_execute_list
  • pcrs_free_job
  • pcrs_free_joblist
  • pcrs_strerror

这是手册页的在线版本。要使用这些函数,请包含头文件pcrs.h并使用链接器标志将您的程序与 PCRS 库链接-lpcrs

于 2013-09-18T17:52:11.523 回答