I want to check rules in my file which looks like 192.168.*.*
*
mean any number. All IPs tested are legal. That's no need to concern special case like 456.123.abc.333
.
Now, I want to do this with c++11 regex. But I don't know how to convert match .
into regex correctly. I will read rules into string, and try to convert it to regex style by function I defined.
In regex, the match for .
is \.
.
But when I try to do this conversion by my function replace
with arguments old_val:.
& new_val\\.
(for escaping \
, I use \\
), the rule 192.168.*.*
will become 192\\.168\\.*\\.*
.
What part of my code need to fix to do this correctly?
Or is there another easier way to do this?
bool check_rule(string CD, string IP){
fstream firewall;
firewall.open("./socks.conf");
string rule;
while(getline(firewall, rule)){
stringstream ss(rule);
string judge, mode, regular;
ss >> judge >> mode >> regular;
//check if mode is correct
if(mode == CD){
replace(regular, ".", "\\.");
replace(regular, "*", "\\d");
cout << "regex :" << regular << endl;
regex regu_expr(regular);
smatch m;
if(regex_match(IP, m, regu_expr)){
return true;
}
}
}
return false;
firewall.close();
}
void replace(string &str, string target, string substi){
size_t pos = 0;
while((pos = str.find(target, pos)) != string::npos){
str.replace(pos, target.size(), substi);
pos += substi.size();
}
}
for rule 192.168.*.*
the check_ruel should return true
if ip like 192.168.231.67
and return false
for IPs like 192.111.22.33
Aucun commentaire:
Enregistrer un commentaire