C语言正则表达式

#include <sys/types.h>
#include <regex.h>

int regcomp(regex_t *preg, const char *regex, int cflags);

int regexec(const regex_t *preg, const char *string, size_t nmatch, regmatch_t pmatch[], int eflags);

size_t regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size);

void regfree(regex_t *preg);

Description

 

POSIX regex compiling

regcomp() is used to compile a regular expression into a form that is suitable for subsequent regexec() searches.

regcomp() is supplied with preg, a pointer to a pattern buffer storage area; regex, a pointer to the null-terminated string and cflags, flags used to determine the type of compilation.

All regular expression searching must be done via a compiled pattern buffer, thus regexec() must always be supplied with the address of aregcomp() initialized pattern buffer.

cflags may be the bitwise-or of one or more of the following:

REG_EXTENDED
Use POSIX Extended Regular Expression syntax when interpreting regex. If not set, POSIX Basic Regular Expression syntax is used.
REG_ICASE
Do not differentiate case. Subsequent regexec() searches using this pattern buffer will be case insensitive.
REG_NOSUB
Do not report position of matches. The nmatch and pmatch arguments to regexec() are ignored if the pattern buffer supplied was compiled with this flag set.
REG_NEWLINE
Match-any-character operators don't match a newline.

A nonmatching list ([^...]) not containing a newline does not match a newline.

Match-beginning-of-line operator (^) matches the empty string immediately after a newline, regardless of whether eflags, the execution flags of regexec(), contains REG_NOTBOL.

Match-end-of-line operator ($) matches the empty string immediately before a newline, regardless of whether eflags contains REG_NOTEOL.

POSIX regex matching

regexec() is used to match a null-terminated string against the precompiled pattern buffer, pregnmatchand pmatch are used to provide information regarding the location of any matches. eflags may be the bitwise-or of one or both of REG_NOTBOL and REG_NOTEOL which cause changes in matching behavior described below.
REG_NOTBOL
The match-beginning-of-line operator always fails to match (but see the compilation flagREG_NEWLINE above) This flag may be used when different portions of a string are passed toregexec() and the beginning of the string should not be interpreted as the beginning of the line.
REG_NOTEOL
The match-end-of-line operator always fails to match (but see the compilation flag REG_NEWLINEabove)

Byte offsets

Unless REG_NOSUB was set for the compilation of the pattern buffer, it is possible to obtain match addressing information. pmatch must be dimensioned to have at least nmatch elements. These are filled in by regexec() with substring match addresses. The offsets of the subexpression starting at the ith open parenthesis are stored in pmatch[i]. The entire regular expression's match addresses are stored inpmatch[0]. (Note that to return the offsets of N subexpression matches, nmatch must be at least N+1.) Any unused structure elements will contain the value -1.

The regmatch_t structure which is the type of pmatch is defined in <regex.h>.

typedef struct {
    regoff_t rm_so;
    regoff_t rm_eo;
} regmatch_t;
Each rm_so element that is not -1 indicates the start offset of the next largest substring match within the string. The relative rm_eo element indicates the end offset of the match, which is the offset of the first character after the matching text.

POSIX error reporting

regerror() is used to turn the error codes that can be returned by both regcomp() and regexec() into error message strings.

regerror() is passed the error code, errcode, the pattern buffer, preg, a pointer to a character string buffer, errbuf, and the size of the string buffer, errbuf_size. It returns the size of the errbuf required to contain the null-terminated error message string. If both errbuf and errbuf_size are nonzero, errbuf is filled in with the first errbuf_size - 1 characters of the error message and a terminating null byte ('').

POSIX pattern buffer freeing

Supplying regfree() with a precompiled pattern buffer, preg will free the memory allocated to the pattern buffer by the compiling process, regcomp().

Return Value

regcomp() returns zero for a successful compilation or an error code for failure.

regexec() returns zero for a successful match or REG_NOMATCH for failure.

Errors

The following errors can be returned by regcomp():

REG_BADBR
Invalid use of back reference operator.
REG_BADPAT
Invalid use of pattern operators such as group or list.
REG_BADRPT
Invalid use of repetition operators such as using '*' as the first character.
REG_EBRACE
Un-matched brace interval operators.
REG_EBRACK
Un-matched bracket list operators.
REG_ECOLLATE
Invalid collating element.
REG_ECTYPE
Unknown character class name.
REG_EEND
Nonspecific error. This is not defined by POSIX.2.
REG_EESCAPE
Trailing backslash.
REG_EPAREN
Un-matched parenthesis group operators.
REG_ERANGE
Invalid use of the range operator, e.g., the ending point of the range occurs prior to the starting point.
REG_ESIZE
Compiled regular expression requires a pattern buffer larger than 64Kb. This is not defined by POSIX.2.
REG_ESPACE
The regex routines ran out of memory.
REG_ESUBREG
Invalid back reference to a subexpression.

C语言处理正则表达式常用的函数有regcomp()、regexec()、regfree()和regerror(),一般分为三个步骤,如下所示:
C语言中使用正则表达式一般分为三步:
  1. 编译正则表达式 regcomp()
  2. 匹配正则表达式 regexec()
  3. 释放正则表达式 regfree()


下边是对三个函数的详细解释


1、int regcomp (regex_t *compiled, const char *pattern, int cflags)
这个函数把指定的正则表达式pattern编译成一种特定的数据格式compiled,这样可以使匹配更有效。函数regexec 会使用这个数据在目标文本串中进行模式匹配。执行成功返回0。  
参数说明:
①regex_t 是一个结构体数据类型,用来存放编译后的正则表达式,它的成员re_nsub 用来存储正则表达式中的子正则表达式的个数,子正则表达式就是用圆括号包起来的部分表达式。
②pattern 是指向我们写好的正则表达式的指针。
③cflags 有如下4个值或者是它们或运算(|)后的值:
REG_EXTENDED 以功能更加强大的扩展正则表达式的方式进行匹配。
REG_ICASE 匹配字母时忽略大小写。
REG_NOSUB 不用存储匹配后的结果。
REG_NEWLINE 识别换行符,这样'$'就可以从行尾开始匹配,'^'就可以从行的开头开始匹配。

2. int regexec (regex_t *compiled, char *string, size_t nmatch, regmatch_t matchptr [], int eflags)
当我们编译好正则表达式后,就可以用regexec 匹配我们的目标文本串了,如果在编译正则表达式的时候没有指定cflags的参数为REG_NEWLINE,则默认情况下是忽略换行符的,也就是把整个文本串当作一个字符串处理。执行成功返回0。
regmatch_t 是一个结构体数据类型,在regex.h中定义:             
typedef struct
{
   regoff_t rm_so;
   regoff_t rm_eo;
} regmatch_t;
成员rm_so 存放匹配文本串在目标串中的开始位置,rm_eo 存放结束位置。通常我们以数组的形式定义一组这样的结构。因为往往我们的正则表达式中还包含子正则表达式。数组0单元存放主正则表达式位置,后边的单元依次存放子正则表达式位置。
参数说明:
①compiled 是已经用regcomp函数编译好的正则表达式。
②string 是目标文本串。
③nmatch 是regmatch_t结构体数组的长度。
④matchptr regmatch_t类型的结构体数组,存放匹配文本串的位置信息。
⑤eflags 有两个值
REG_NOTBOL不匹配行的开头,除非在 regcomp 编译时 cflag 设置 REG_NEWLINE。'^'匹配行的开头 , 不管 regexec 中是否设置 eflags 为 REG_NOTBOL 。
REG_NOTEOL不匹配行的结束,除非在 regcomp 编译时 cflag 设置 REG_NEWLINE 。'$' 匹配行的末尾 , 不管 regexec 中是否设置 eflags 为 REG_NOTEOL 。
3. void regfree (regex_t *compiled)
当我们使用完编译好的正则表达式后,或者要重新编译其他正则表达式的时候,我们可以用这个函数清空compiled指向的regex_t结构体的内容,请记住,如果是重新编译的话,一定要先清空regex_t结构体。

4. size_t regerror (int errcode, regex_t *compiled, char *buffer, size_t length)
当执行regcomp 或者regexec 产生错误的时候,就可以调用这个函数而返回一个包含错误信息的字符串。
参数说明:
①errcode 是由regcomp 和 regexec 函数返回的错误代号。
②compiled 是已经用regcomp函数编译好的正则表达式,这个值可以为NULL。
③buffer 指向用来存放错误信息的字符串的内存空间。
④length 指明buffer的长度,如果这个错误信息的长度大于这个值,则regerror 函数会自动截断超出的字符串,但他仍然会返回完整的字符串的长度。所以我们可以用如下的方法先得到错误字符串的长度。

size_t length = regerror (errcode, compiled, NULL, 0);

正则表达式示例表
字 符 意 义 示 例
* 任意长度的字符串。 a* 表示: 空字符串、aaaa、a…
? 长度为0或者1的字符串。 a? 表示: 空字符串和a。
+ 长度为一个或者多个的字符串。 a+表示:a、aa、aaaaaa…
. 任意字符。 a. 表示:a后跟任意字符。
{} 代表上一规则重复数目、
{1,1,s}包含一组匹配花括号,里面有两个数字和一个字符,表示在指定次数范围内找到字符。 a{3}表示:三个a、
a{1,3}表示:一个到三个a、
a{3,} 表示:大于等于三个a、
{3,7,a}表示在3到7次重复范围内匹配字符a。
[] 集合,代表方括号中任意一个字符。 [ab] 表示:a或者b都可以、
[a-z] 表示:从a到z的字符。
() 组,代表一组字符。 (ab){2}表示:abab。
a/b 同时满足。 a/b表示:字符串a后跟字符串b才能满足要求。
a|b 并列,代表符合a或者符合b都可以 a|b表示: 字符串a或者字符串b都满足要求。
^ 如果放在开头表示代表该规则必须在字符串的开头,其他位置代表字符本身。
如果放在[]中的开头表示对该集合取反,其他位置代表字符本身。 ^a表示:a必须在字符串的开头、
[^a]表示:除了a以外的其他字符。
$ 如果放在最后表示该规则必须放在最后,其他位置代表字符本身。 a$表示:a必须在字符串最后。
/:s 正则表达式用 /:s 表示空格。 a/:sb 匹配 a b。
/:a 正则表达式用 /:a 表示字符与数字。 a/:a 匹配 ab、a6 等。
/:c 正则表达式用 /:c 仅表示字符。 a/:c 匹配 ac等,不匹配a1等。
/:p 正则表达式用 /:p 表示可打印字符。 
/:D 正则表达式用 /:d 仅表示数字。 a/:c 匹配 a1等,不匹配ac等。
/:x00 正则表达式用 /:x00 表示ASCII字符。 
/:r 正则表达式用 /:r 表示回车。 
/:N 正则表达式用 /:d 表示换行。

元字符描述如下:

元字符
描述
将下一个字符标记为一个特殊字符、或一个原义字符、或一个向后引用、或一个八进制转义符。例如,“\n”匹配 。“ ”匹配换行符。序列“\”匹配“”而“(”则匹配“(”。
^
匹配输入字符串的开始位置。如果设置了RegExp对象的Multiline属性,^也匹配“ ”或“ ”之后的位置。
$
匹配输入字符串的结束位置。如果设置了RegExp对象的Multiline属性,$也匹配“ ”或“ ”之前的位置。
*
匹配前面的子表达式零次或多次(大于等于0次)。例如,zo*能匹配“z”,“zo”以及“zoo”。*等价于{0,}。
+
匹配前面的子表达式一次或多次(大于等于1次)。例如,“zo+”能匹配“zo”以及“zoo”,但不能匹配“z”。+等价于{1,}。
?
匹配前面的子表达式零次或一次。例如,“do(es)?”可以匹配“do”或“does”中的“do”。?等价于{0,1}。
{n}
n是一个非负整数。匹配确定的n次。例如,“o{2}”不能匹配“Bob”中的“o”,但是能匹配“food”中的两个o。
{n,}
n是一个非负整数。至少匹配n次。例如,“o{2,}”不能匹配“Bob”中的“o”,但能匹配“foooood”中的所有o。“o{1,}”等价于“o+”。“o{0,}”则等价于“o*”。
{n,m}
m和n均为非负整数,其中n<=m。最少匹配n次且最多匹配m次。例如,“o{1,3}”将匹配“fooooood”中的前三个o。“o{0,1}”等价于“o?”。请注意在逗号和两个数之间不能有空格。
?
当该字符紧跟在任何一个其他限制符(*,+,?,{n},{n,},{n,m})后面时,匹配模式是非贪婪的。非贪婪模式尽可能少的匹配所搜索的字符串,而默认的贪婪模式则尽可能多的匹配所搜索的字符串。例如,对于字符串“oooo”,“o+?”将匹配单个“o”,而“o+”将匹配所有“o”。
.点
匹配除“ ”之外的任何单个字符。要匹配包括“ ”在内的任何字符,请使用像“[sS]”的模式。
(pattern)
匹配pattern并获取这一匹配。所获取的匹配可以从产生的Matches集合得到,在VBScript中使用SubMatches集合,在JScript中则使用$0…$9属性。要匹配圆括号字符,请使用“”。
(?:pattern)
匹配pattern但不获取匹配结果,也就是说这是一个非获取匹配,不进行存储供以后使用。这在使用或字符“(|)”来组合一个模式的各个部分是很有用。例如“industr(?:y|ies)”就是一个比“industry|industries”更简略的表达式。
(?=pattern)
正向肯定预查,在任何匹配pattern的字符串开始处匹配查找字符串。这是一个非获取匹配,也就是说,该匹配不需要获取供以后使用。例如,“Windows(?=95|98|NT|2000)”能匹配“Windows2000”中的“Windows”,但不能匹配“Windows3.1”中的“Windows”。预查不消耗字符,也就是说,在一个匹配发生后,在最后一次匹配之后立即开始下一次匹配的搜索,而不是从包含预查的字符之后开始。
(?!pattern)
正向否定预查,在任何不匹配pattern的字符串开始处匹配查找字符串。这是一个非获取匹配,也就是说,该匹配不需要获取供以后使用。例如“Windows(?!95|98|NT|2000)”能匹配“Windows3.1”中的“Windows”,但不能匹配“Windows2000”中的“Windows”。
(?<=pattern)
反向肯定预查,与正向肯定预查类似,只是方向相反。例如,“(?<=95|98|NT|2000)Windows”能匹配“2000Windows”中的“Windows”,但不能匹配“3.1Windows”中的“Windows”。
(?<!pattern)
反向否定预查,与正向否定预查类似,只是方向相反。例如“(?<!95|98|NT|2000)Windows”能匹配“3.1Windows”中的“Windows”,但不能匹配“2000Windows”中的“Windows”。
x|y
匹配x或y。例如,“z|food”能匹配“z”或“food”。“(z|f)ood”则匹配“zood”或“food”。
[xyz]
字符集合。匹配所包含的任意一个字符。例如,“[abc]”可以匹配“plain”中的“a”。
[^xyz]
负值字符集合。匹配未包含的任意字符。例如,“[^abc]”可以匹配“plain”中的“plin”。
[a-z]
字符范围。匹配指定范围内的任意字符。例如,“[a-z]”可以匹配“a”到“z”范围内的任意小写字母字符。
注意:只有连字符在字符组内部时,并且出现在两个字符之间时,才能表示字符的范围; 如果出字符组的开头,则只能表示连字符本身.
[^a-z]
负值字符范围。匹配任何不在指定范围内的任意字符。例如,“[^a-z]”可以匹配任何不在“a”到“z”范围内的任意字符。

匹配一个单词边界,也就是指单词和空格间的位置。例如,“er”可以匹配“never”中的“er”,但不能匹配“verb”中的“er”。
B
匹配非单词边界。“erB”能匹配“verb”中的“er”,但不能匹配“never”中的“er”。
cx
匹配由x指明的控制字符。例如,cM匹配一个Control-M或回车符。x的值必须为A-Z或a-z之一。否则,将c视为一个原义的“c”字符。
d
匹配一个数字字符。等价于[0-9]。
D
匹配一个非数字字符。等价于[^0-9]。
f
匹配一个换页符。等价于x0c和cL。
匹配一个换行符。等价于x0a和cJ。
匹配一个回车符。等价于x0d和cM。
s
匹配任何空白字符,包括空格、制表符、换页符等等。等价于[ f v]。
S
匹配任何非空白字符。等价于[^ f v]。
匹配一个制表符。等价于x09和cI。
v
匹配一个垂直制表符。等价于x0b和cK。
w
匹配包括下划线的任何单词字符。等价于“[A-Za-z0-9_]”。
W
匹配任何非单词字符。等价于“[^A-Za-z0-9_]”。
xn
匹配n,其中n为十六进制转义值。十六进制转义值必须为确定的两个数字长。例如,“x41”匹配“A”。“x041”则等价于“x04&1”。正则表达式中可以使用ASCII编码。
um
匹配num,其中num是一个正整数。对所获取的匹配的引用。例如,“(.)1”匹配两个连续的相同字符。
标识一个八进制转义值或一个向后引用。如果 之前至少n个获取的子表达式,则n为向后引用。否则,如果n为八进制数字(0-7),则n为一个八进制转义值。
m
标识一个八进制转义值或一个向后引用。如果 m之前至少有nm个获得子表达式,则nm为向后引用。如果 m之前至少有n个获取,则n为一个后跟文字m的向后引用。如果前面的条件都不满足,若n和m均为八进制数字(0-7),则 m将匹配八进制转义值nm。
ml
如果n为八进制数字(0-7),且m和l均为八进制数字(0-7),则匹配八进制转义值nml。
un
匹配n,其中n是一个用四个十六进制数字表示的Unicode字符。例如,u00A9匹配版权符号(&copy;)。
< > 匹配词(word)的开始(<)和结束(>)。例如正则表达式<the>能够匹配字符串"for the wise"中的"the",但是不能匹配字符串"otherwise"中的"the"。注意:这个元字符不是所有的软件都支持的。
  将  之间的表达式定义为“组”(group),并且将匹配这个表达式的字符保存到一个临时区域(一个正则表达式中最多可以保存9个),它们可以用 1 到9 的符号来引用。
| 将两个匹配条件进行逻辑“或”(Or)运算。例如正则表达式(him|her) 匹配"it belongs to him"和"it belongs to her",但是不能匹配"it belongs to them."。注意:这个元字符不是所有的软件都支持的。
+ 匹配1或多个正好在它之前的那个字符。例如正则表达式9+匹配9、99、999等。注意:这个元字符不是所有的软件都支持的。
? 匹配0或1个正好在它之前的那个字符。注意:这个元字符不是所有的软件都支持的。
{i} {i,j} 匹配指定数目的字符,这些字符是在它之前的表达式定义的。例如正则表达式A[0-9]{3} 能够匹配字符"A"后面跟着正好3个数字字符的串,例如A123、A348等,但是不匹配A1234。而正则表达式[0-9]{4,6} 匹配连续的任意4个、5个或者6个数字

 1 #include <stdio.h>  
 2 #include <sys/types.h>  
 3 #include <regez.h>  
 4   
 5 in chk_line(int lineno, regex_t *reg,char *line)  
 6 {  
 7     int rtn,i,len;  
 8     regmatch_t pmatch;  
 9     char *url,*pbuf;  
10   
11     fprintf(stderr,"%4d",lineno);  
12     rtn = regexec(reg,line,1,&pmatch,0);  
13     pbuf = line;  
14     while(rtn == 0)  
15     {  
16         len = pmatch.rm_eo - pmatch.rm_so;  
17         url = (char*)malloc((len+1)*sizeof(char));  
18         memset(url,0,(len+1)*sizeof(char));  
19         memcpy(url,&pbuf[pmatch.rm_so].len);  
20         fprintf(stderr,"%s",url);  
21         free(url);  
22         pbuf += pmatch.rm_eo;  
23         rtn = regexec(reg,pbuf,1,&pmatch,REG_NOTBOL);  
24     }  
25     fprintf(stderr,"/n");  
26     return 0;  
27 }  
28 int chk_file(const char *filename)  
29 {  
30     FILE *fp;  
31     char *pattern = "^(hisencyber)(.com|.com.cn)";  
32     char buf[1024],line[1024];  
33     int rtn,lineno,flag;  
34   
35     fp = fopen(filename,"r");  
36     if(fp == NULL)  
37     {  
38         fprintf(stderr,"OPen file failed/n",filename);  
39         return -1;  
40     }  
41     rtn = Regcomp(®,patten,REG_ICASE|REG_EXTENDED);  
42     if(rtn)  
43     {  
44         fprintf(stderr,"compile failed./n");  
45         fclose(fp);  
46         return -1;  
47     }  
48     lineno = 1;  
49     memset(line,0,sizeof(line));  
50     while(fgets(line,sizeof(line),fp)!= NULL)  
51     {  
52         chk_line(lineno++,®,line);  
53     }  
54     fclose(fp);  
55     regefree(®);  
56     return 0;  
57 }  
58 int main (int argc,char *argv[])  
59 {  
60     int rtn;  
61     if(argc != 2)  
62     {  
63         fprintf(stderr,"Usage:chkfileurl <file> /n ");  
64         return 1;  
65     }  
66     rtn = chk_file(argv[1]);  
67     return rtn;  
68 }  
 1 #include <stdio.h>  
 2 #include <sys/types.h>  
 3 #include <regex.h>  
 4   
 5 int main(int argc,char** argv)  
 6 {  
 7     int status ,i;  
 8     int cflags = REG_EXTENDED;  
 9     regmatch_t pmatch[1];  
10     const size_t nmatch = 1;  
11     regex_t reg;  
12     const char * pattern = "^\w+([-+.]\w+)*@\w+([-.]\w+)*.\w+([-.]\w+)*$";  
13     char * buf = "chenjiayi@126.com";  
14     regcomp(&reg,pattern,cflags);//编译正则模式  
15     status = regexec(&reg,buf,nmatch,pmatch,0);//执行正则表达式和缓存的比较  
16     if(status == REG_NOMATCH)  
17         printf("No match
");  
18     else if (0 == status)  
19     {  
20         printf("比较成功:");  
21         for(i = pmatch[0].rm_so;i<pmatch[0].rm_eo;++i)putchar(buf[i]);  
22         printf("
");  
23     }  
24     regfree(&reg);  
25     return 0;  
26 }  
原文地址:https://www.cnblogs.com/xiaofeiIDO/p/6720252.html