Linux C-language processing regular expressions

Source: Internet
Author: User

Linux C language Processing regular expression--regex.h specific functions introduction to compiling regular expression functions
int Const Char int cflags);

Where Preg is used to save compiled regular expressions, and regex is the regular expression we write. Cflags the flag bit after.

First talk about regex_t structure:

For this struct, we just need to remember that it is a compiled regular expression, followed by a compiled regular expression, which is more efficient than using the original regular expression we wrote ourselves. Also, be aware that regex_t has a member re_nsub, which represents "the number of Zhong expressions ". The so-called "sub-Regular expression" is the regular expression inside the parentheses. Maybe it's a little confusing. It's okay, take it slow! one of the main purposes of using regular expressions is to extract the parts that satisfy the conditions . For example, there is a string username= star &sex= Female, now we want to extract the user name, is also the "star", then our regular expression should be written: Username= ([^&]*) &, that is, will match "star" 's regular expression into parentheses, as a subexpression of the entire expression. After we execute the REGEXEC function, we can get "star" (Back Again).

Then say Cflags:

The cflags values are: reg_extended, Reg_icase, Reg_nosub, and Reg_newline. These four values can be used alone or in conjunction with a bitwise and union.

which

Reg_extended:

This means that the regular expression syntax of an extension is used when interpreting the regular expression. The POSIX specification divides the implementation of regular expressions into two types: a basic regular expression (BRE) and an extended regular expression (ERE).

What's the difference between Bre and ere? It's just a different meta-character! In the BRE mode, only ^, $, is recognized. , [,], * these are meta characters, and all other characters are recognized as literal characters. In the Ere, the (,), {,} 、?、 + |, and other metacharacters (and their related functions) are added. The grep command supports BRE by default, and the-e option is required to support ere.

Reg_icase:

If this flag is used when compiling a regular expression, the case is ignored when matching with the Regexec () function.

Reg_nosub:

If you use this option to get a compiled regular expression, the Nmatch and Pmatch parameters of regexec () will be ignored when used by the regexec () function that follows (later)

Reg_newline:

At first, my understanding of the sign was very vague, and many people on the Internet were not clear about the explanation. after my repeated experiments, I finally understood.

In fact, the role of Reg_newline two:

1, make ^ and $ valid.

2. Definitely does not match line breaks.

I believe everyone has seen the man page in Linux. For the explanation of the reg_newline, four words were used in the man page.

Let's look at the latter two sentences first:

Match-beginning-of-line operator (^) matches the empty string immediately after a newline, regardless of whether EFLA GS, 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 con Tains Reg_noteol.

The meaning of these two sentences is that it is the start position of the match line, the $ match the end position of the line (if Reg_newline is not used, the two characters will be treated as ordinary characters). and invalidates Reg_notbol and Reg_noteol.

Give two examples:

There are strings:

username=xinger&sex=girl&age=22\ r \n school=bit&husband=qinger\&like=study &look=pretty\ r \ n

If we do not use the Reg_newline flag, then the regular expression ^school= ([^&]*) will not match, as this ^ is interpreted as a normal character, not as a line start.

If we add the Reg_newline flag, it will be matched to School=bit, at which point the ^ is no longer a normal character, but matches the beginning of a line.

Another example is the regular expression age= ([^$]*), if Reg_newline is not used, it will match:

age=22\r\nschool=bit&husband=qinger\r\n&like=study&look=pretty\r\n

Or because $ is interpreted as an ordinary character,

For example, we add a $ to the original string, which becomes

username=xinger&sex=girl&age=22\ r \ nschool= $BIT &husband=$qinger\ r& Like=study&look=pretty\ r \ n

The match result becomes age=22\r\nschool=, the reason is still: the $ as a normal character.

Before we look at the first two sentences:

Match-any-character operators don ' t match a newline.

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

The meaning of these two sentences is to ensure that the line break is not matched. For example, the first sentence, meaning that matches any character of the metacharacters also does not match the new Line (good chaos). What do you mean? For example, point (.) would have matched all the characters (note that the POSIX midpoint matches all characters!!!) It's not the same as what we usually learn. However, if the Reg_newline flag is used, the line break \ r \ n is not matched.

Let's give an example:

There are strings:

username=xinger&sex=girl&age=22\ r \ nschool=bit&husband= $qinger\ r \&like=study &look=pretty\ r \ n

There is a regular expression: sex= ([^@]*), if there is no reg_newline flag, the matching result is:

sex=girl&age=22 \r \ nschool=bit&husband= $qinger \r\n&like=study&look=pretty \ r \ n

Because [^@] matches all characters that are not @. But if we add reg_newline, then the match result is: sex=girl&age=22, because Reg_newline guaranteed never match line break !!! In fact, the equivalent of [^@\r\n] not add reg_newline.

For example, there is a regular expression sex= (. *), which we mentioned earlier: the point matches any character in POSIX (except '+ '), so the point also matches the newline character, so the match result is:

sex=girl&age=22\ r \ nschool=bit&husband= $qinger\ r \&like=study&look=pretty \ r \ n

However, if we use reg_newline, we guarantee that the line break will not match, and the matching result becomes: sex=girl&age=22.

Finally, say the return value:

Successful return 0, failure can use Regerror to obtain the failure code.

Matching with compiled regular expressions
int regexec (constconstchar *string, size_t nmatch,                     int eflags);

The Regexec function matches the string content with the regular expression compiled in the previous step preg and saves the matching result in the Pmatch array as a record byte offset.

First look at the regmatch_t structure:

regmatch_t is a struct data type, defined in Regex.h:

struct {   regoff_t rm_so;   regoff_t Rm_eo;} regmatch_t;

The Regexec function populates the Pmatch structure with the starting and ending addresses of the matched substrings, pmatch[0] corresponds to the start and end address of the matching result of the entire regular expression, and pmatch[i] corresponds to the ending address of the sub-match string that is stored. (Rm_so represents the offset from the first address from the starting position, Rm_eo represents the offset of the end position from the first address of +1, and if the Rm_so is-1 indicates that the subexpression does not match). Nmatch represents the number of elements in an array of pmatch structures, which should at least be the number of sub-expressions plus 1 (because the 0 subscript stores the matching result of the entire expression).

Then say EFlags:

First of all, if the reg_newline variable is used in Regcomp, this flag bit is invalid!

This flag bit has two values: Reg_notbol and Reg_noteol, the function is: if the corresponding flag bit is set, then contains ^ or $, and the meaning is a line start, or end (such as ^ can also be interpreted as non), then the regular expression will never match!!!

Finally, say the return value:

A successful return of 0,reg_nomatch indicates a failure.

To convert an error code to an error message
size_t regerror (intconstChar *errbuf,                       size_t errbuf_size);

This function is used to convert the error code returned by Regcomp or regexec to the error string information.

The parameter Errcode represents the error code returned by the two functions, Preg is the Regcomp compiled regular expression, Errbuf is used to store the error message string, Errbuf_size is the size of errbuf.

Releasing the regex_t structure
void RegFree (regex_t *preg);

The Regcomp function fills in the elements of the regex_t struct, which requires a storage space for some elements, and the RegFree function frees the space.

Remember to finally call RegFree to free up space, otherwise it will cause a memory leak.

Finally, a small example is attached:
#include <sys/types.h>#include<regex.h>#include<stdio.h>#include<string.h>#include<stdlib.h>Static intCompile_regex (regex_t* compiled,Const Char*pattern) {        Charerrbuf[1024x768]; interr; if((Err=regcomp (compiled,pattern,reg_extended| reg_icase))! =0) {regerror (Err,compiled,errbuf,sizeof(ERRBUF)); printf ("err:%s\n", ERRBUF); return-1; }     return 0;}intMain () {Const Char*dest ="username=xinger&sex=girl&age=22\r\nschool=bit&husband= $qinger \r\n&like=study&look= pretty\r\n"; printf ("The original data is: \n%s\n", dest); Const Char*pattern ="school= ([^&]*)"; interr; Charerrbuf[1024x768];    Regex_t compiled; if(Err = Regcomp (&compiled,pattern,reg_extended| reg_icase))! =0) {Regerror (err,&compiled,errbuf,sizeof(ERRBUF)); printf ("err:%s\n", ERRBUF); return-1; } regmatch_t pmatch[3]; Err= Regexec (&compiled,dest,3, Pmatch,reg_notbol); if(Err! =0) {printf ("not matched successfully! \ n"); return-1; }    inti =0;  for(; I <= (int) compiled.re_nsub;i++)    {        if(Pmatch[i].rm_so = =-1)            Continue; intLen = Pmatch[i].rm_eo-Pmatch[i].rm_so; Char*value = (Char*)malloc(Len +1); if(Value = =NULL)return-1; memset (Value,0, Len +1); memcpy (Value,dest+Pmatch[i].rm_so,len); printf ("the extracted values are:%s\n", value);  Free(value); } regfree (&compiled);//Remember to release it at the end, or it will cause a memory leak.        return 0;}

If you think it's useful to you, just a nice one.

Linux C language processing regular expressions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.