#include <iostream>
#include <vector>
#include <utility>
#include <string>

using namespace std;

vector<pair<string, bool> > rules;
vector<string> legal_packets;

bool match(string pattern, string s) {
    for (int i = 0; i < pattern.size(); i++) {
        if (pattern[i] == '?') continue;
        if (pattern[i] != s[i]) return false;
    }
    return true;
}

bool can_access(string addr) {
    for (int i = rules.size()-1; i >= 0; i--) {
        if (match(rules[i].first, addr)) {
            if (rules[i].second) {
                return true;
            } else {
                return false;
            }
        }
    }
    return false;
}

int main() {
    int n, m;
    while (cin >> n >> m) {
        if (n == 0 && m == 0) break;
        rules.clear(), legal_packets.clear();
        for (int i = 0; i < n; i++) {
            string permission, src_pattern, dst_pattern;
            cin >> permission >> src_pattern >> dst_pattern;
            if (permission == "permit") {
                rules.push_back(make_pair(src_pattern + ' ' + dst_pattern, true));
            } else {
                rules.push_back(make_pair(src_pattern + ' ' + dst_pattern, false));
            }
        }

        for (int i = 0; i < m; i++) {
            string src_addr, dst_addr, msg;
            cin >> src_addr >> dst_addr >> msg;
            if (can_access(src_addr + ' ' + dst_addr)) {
                legal_packets.push_back(src_addr + ' ' + dst_addr + ' ' + msg);
            }
        }

        cout << legal_packets.size() << endl;
        for (int i = 0; i < legal_packets.size(); i++) {
            cout << legal_packets[i] << endl;
        }
    }
    return 0;
}