问题描述
我经过一些简单的例子和如何在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(®ex, "^a[[:alnum:]]", 0);
if (reti) {
fprintf(stderr, "Could not compile regex\n");
exit(1);
}
/* Execute regular expression */
reti = regexec(®ex, "abc", 0, NULL, 0);
if (!reti) {
puts("Match");
}
else if (reti == REG_NOMATCH) {
puts("No match");
}
else {
regerror(reti, ®ex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
exit(1);
}
/* Free memory allocated to the pattern buffer by regcomp() */
regfree(®ex);
另外,你可能想看看,在C.的Perl兼容的正前pressions库Perl的语法为pretty多,使用Java,Python使用相同的语法,和一些其他语言。该POSIX语法是的grep
, SED
,六$ C $使用的语法C>等。
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:例子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!