C中的正则表达式:示例? [英] Regular expressions in C: examples?

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

问题描述

我正在寻找一些关于如何在 ANSI C 中使用正则表达式的简单示例和最佳实践.man 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.

推荐答案

正则表达式实际上不是 ANSI C 的一部分.听起来您可能在谈论 POSIX 正则表达式库,它与大多数(全部?)*尼克斯.这是在 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
");
    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
", msgbuf);
    exit(1);
}

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

或者,您可能想查看 PCRE,这是一个用于 C 语言中与 Perl 兼容的正则表达式的库.Perl 语法与 Java、Python 和许多其他语言中使用的语法几乎相同.POSIX语法是grepsedvi等使用的语法

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.

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

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