普通的前pressions在C:例子? [英] Regular expressions in C: examples?

查看:103
本文介绍了普通的前pressions在C:例子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经过一些简单的例子和​​如何在ANSI C.使用常规的前pressions最佳实践男人regex.h 并没有提供太大的帮助

I'm after some simple examples and best practices of how to use regular expressions in ANSI C. man regex.h does not provide that much help.

推荐答案

正前pressions其实不是ANSI C的一部分,这听起来像你可能会谈论POSIX正前pression库,附带大多数(所有?)* nixes。下面是用C使用POSIX正则表达式的例子(根据这个):

Regular expressions actually aren't part of ANSI C. It sounds like you might be talking about the POSIX regular expression library, which comes with most (all?) *nixes. Here's an example of using POSIX regexes in C (based on this):

#include <regex.h>        
regex_t regex;
int reti;
char msgbuf[100];

/* Compile regular expression */
reti = regcomp(&regex, "^a[[:alnum:]]", 0);
if (reti) {
    fprintf(stderr, "Could not compile regex\n");
    exit(1);
}

/* Execute regular expression */
reti = regexec(&regex, "abc", 0, NULL, 0);
if (!reti) {
    puts("Match");
}
else if (reti == REG_NOMATCH) {
    puts("No match");
}
else {
    regerror(reti, &regex, msgbuf, sizeof(msgbuf));
    fprintf(stderr, "Regex match failed: %s\n", msgbuf);
    exit(1);
}

/* Free memory allocated to the pattern buffer by regcomp() */
regfree(&regex);

另外,你可能想看看 PCRE ,在C.的Perl兼容的正前pressions库Perl的语法为pretty多,使用Java,Python使用相同的语法,和一些其他语言。该POSIX语法是的grep SED 等。

Alternatively, you may want to check out PCRE, a library for Perl-compatible regular expressions in C. The Perl syntax is pretty much that same syntax used in Java, Python, and a number of other languages. The POSIX syntax is the syntax used by grep, sed, vi, etc.

这篇关于普通的前pressions在C:例子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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