POSIX C正则表达式
(2019年04月02日)
man 2 regex
拯救世界。
GNU C支持两种正则表达式标准,通过引入regex.h
可以使用GNU C标准,如果定义_POSIX_C_SOURCE
,可以使用POSIX.2标准。
编译
数据结构:regex_t
,程序只需要关心re_nsub
成员。新建完此类数据结构后即可进行编译,函数原型为
int regcomp (regex_t *restrict compiled, const char *restrict pattern, int cflags)
regcomp
将正则表达式编译并存储到*compiled
对象中,如果成功,返回0
,否则返回错误的代码(见10.3.1)。
匹配
函数定义:
int regexec (const regex_t *restrict compiled,const char *restrict string, size_t nmatch, regmatch_t matchptr[restrict], int eflags)
如果nmatch == 0
或者使用了REG_NOSUB
flag,那么只对整个字符串进行匹配,如果匹配成功返回0
,否则返回非零值(见10.3.3)。
否则,当regexec
匹配到了括号内的子表达式时,函数会记录匹配的字符串到matchptr
中。数据结构regmatch_t
包含两个偏移量:rm_so
和rm_eo
表示匹配的起始偏移量和终止偏移量。数组matchptr
的0号元素存储整个正则表达式的匹配,其他元素(1, 2...)按先后出现顺序存储括号内的子表达式的匹配信息。
清理
函数定义:
void regfree (regex_t *compiled)
清除已编译的正则表达式对象,但是不会释放compiled对象的内存。
References
GNU Man Pages: https://www.gnu.org/software/libc/manual/html_node/Regular-Expressions.html