#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <tuple>
#include <utility>
#include <vector>
using namespace std;

#define REP(i, a, b) for(int i = (a); i < (int)(b); ++i)
#define rep(i, n) REP(i, 0, n)
#define ALL(x) begin(x), end(x)

bool check(const string &str, const string &pattern) {
	rep(i, str.size()) {
		if(pattern[i] != '?' && str[i] != pattern[i]) return false;
	}
	return true;
}

int main() {
	cin.tie(nullptr);
	ios::sync_with_stdio(false);

	for(int n, m; cin >> n >> m && (n | m);) {
		vector<pair<bool, string>> rules;

		rep(i, n) {
			string which, source, destination;
			cin >> which >> source >> destination;

			const string sum = source + destination;
			const bool is_permit = (which[0] == 'p');
			rules.emplace_back(is_permit, sum);
		}

		reverse(ALL(rules));
		vector<tuple<string, string, string>> match;
		match.reserve(m);

		rep(i, m) {
			string source, destination, body;
			cin >> source >> destination >> body;

			const string sum = source + destination;

			for(const auto &rule : rules) {
				if(check(sum, rule.second)) {
					if(rule.first) match.emplace_back(source, destination, body);
					break;
				}
			}
		}

		cout << match.size() << endl;
		for(const auto &e : match) {
			cout << get<0>(e) << " " << get<1>(e) << " " << get<2>(e) << endl;
		}
	}

	return EXIT_SUCCESS;
}