如何在C中使用正则表达式? [英] How to use regular expressions in C?

查看:52
本文介绍了如何在C中使用正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用 C 编写一个解析字符串的小程序.我想使用正则表达式,因为我已经使用它们多年了,但我不知道如何在 C 中做到这一点.我找不到任何直接的例子(即,使用这个库",这个是方法论").

谁能给我举个简单的例子?

解决方案

您可以使用PCRE:><块引用>

PCRE 库是一组使用与 Perl 5 相同的语法和语义来实现正则表达式模式匹配的函数. PCRE 有自己的原生 API,以及一组对应于 POSIX 正则表达式 API 的包装函数.PCRE 库是免费的,即使用于构建商业软件也是如此.

有关 PCRE 示例,请参阅 pcredemo.c.

如果不能使用 PCRE,POSIX 正则表达式 支持大概是在您的系统上可用(正如@tinkertim 指出的).对于 Windows,您可以使用 gnuwin Regex for Windows 包.

regcomp 文档包括下面的例子:

#include /** 匹配字符串中的扩展正则表达式* 模式,将错误视为不匹配.** 匹配返回1,不匹配返回0.*/整数匹配(const char *string,char *pattern){内部状态;regex_t re;如果(regcomp(&re,模式,REG_EXTENDED|REG_NOSUB)!= 0){返回(0);/* 报告错误.*/}status = regexec(&re, string, (size_t) 0, NULL, 0);regfree(&re);如果(状态!= 0){返回(0);/* 报告错误.*/}返回(1);}

I need to write a little program in C that parses a string. I wanted to use regular expressions since I've been using them for years, but I have no idea how to do that in C. I can't find any straight forward examples (i.e., "use this library", "this is the methodology").

Can someone give me a simple example?

解决方案

You can use PCRE:

The PCRE library is a set of functions that implement regular expression pattern matching using the same syntax and semantics as Perl 5. PCRE has its own native API, as well as a set of wrapper functions that correspond to the POSIX regular expression API. The PCRE library is free, even for building commercial software.

See pcredemo.c for a PCRE example.

If you cannot use PCRE, POSIX regular expression support is probably available on your system (as @tinkertim pointed out). For Windows, you can use the gnuwin Regex for Windows package.

The regcomp documentation includes the following example:

#include <regex.h>

/*
 * Match string against the extended regular expression in
 * pattern, treating errors as no match.
 *
 * Return 1 for match, 0 for no match.
 */

int
match(const char *string, char *pattern)
{
    int    status;
    regex_t    re;

    if (regcomp(&re, pattern, REG_EXTENDED|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);
}

这篇关于如何在C中使用正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆