The ad filtering list defined by Adblock plus is very useful. Here we will analyze the ad filtering rules of Adblock plus.
! Start to indicate comments
* Wildcard, matching any string
@ Indicates the White List starting with this,
| Start or end with this statement, which indicates that the start or end position is strictly matched and no other content exists.
| Protocol rules are ignored for matching, such as HTTP and HTTPS.
^ The delimiter matches characters other than numbers, letters,-,., and %.
$ Specify the filter type, such as image or script.
According to Adblock Plus, these are eventually converted into regular expressions for processing. It is not clear how to implement them.
In most cases, the most time-consuming operation is the matching problem, type, and protocol information that can be analyzed based on the URL, which is easy to separate,
So here we will focus on how to implement the core *, ^ matching, and reduce the number of nesting times through a patternstep.
/*
Get a much bigger step *.
*/
Static inline
Int patternstep (const char * s,
Const char * P)
{
// You can skip several times based on the next character
Char temp [8];
Int step = 0;
Const char * t = P;
While (* t! = '*' & * T! = '^ '&&
* T! = '\ 0 ')
{
Step ++;
T ++;
}
If (! Step) // prevents only one wildcard such as ^ ,*
Return 1;
Memset (temp, 0, sizeof (temp ));
Strncpy (temp, P, min (sizeof (temp)-1, step ));
Printf ("temp = % s, step = % d \ n", temp, step );
Const char * res = strfind (S, temp );
If (! Res) // not found
Return strlen (s); // move the entire string
Else
Return max (1, res-S); // locate the first matched string
}
/*
Test if a given string and a pattern
Matches use Adblock plus rule
Give a string s and a pattern P,
If they match, return 1, then return 0
*/
Bool adbmatch (const
Char * s, const char *
P, bool casesensitivie = true ){
For (;;){
Switch (* P ++ ){
Case '*': // match 0-n of any characters
// You can skip several times based on the next character
If (! * P) return true; // do
Trailing * quickly
While (! Adbmatch (S,
P, casesensitivie ))
{
If (! * S) return false;
S + = patternstep (S, P );
}
Return true;
Case '^ ':
If (isseperator (* s ))
{
S ++;
Break;
}
Else
Return false; // CT
Sepetor,
Case '\ 0': // end of Pattern
Return! * S;
Default:
If
(Getcasechar (* s ++, casesensitivie )! =
Getcasechar (* (P-1), casesensitivie) return false;
Break;
}
}
}