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

#define dump(a) (cerr << #a << " = " << (a) << endl)
#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)

constexpr int LEN = 8;

int main() {
  for(int n, m; cin >> n >> m && (n | m);) {
	vector<tuple<bool, vector<int>, string>> rules;
	
	set<string> permit, deny;

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

	  const string sum = source + destination;
	  vector<int> pos;
	  rep(j, sum.size()) {
		if(sum[j] == '?') pos.emplace_back(j);
	  }

	  const bool is_permit = (which[0] == 'p');
	  auto &S = (is_permit ? permit : deny);

	  rules.emplace_back(is_permit, pos, sum);
	  S.insert(sum);
	}

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

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

	  for(const auto &rule : rules) {
		string sum = source + destination;

		for(const auto &pos : get<1>(rule)) {
		  sum[pos] = '?';
		}

		if(get<2>(rule) == sum) {
		  if(get<0>(rule)) 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 0;
}