Neo has a complex matrix script. The matrix script is a $N$ X $\mbox{M}$ grid of strings. It consists of alphanumeric characters, spaces and  symbols (!,@,#,$,%,&).

To decode the script, Neo needs to read each column and select only the alphanumeric characters and connect them. Neo reads the column from top to bottom and starts reading from the leftmost column.

If there are symbols or spaces between two alphanumeric characters of the decoded script, then Neo replaces them with a single space '' for better readability.  

Neo feels that there is no need to use 'if' conditions for decoding.

Alphanumeric characters consist of: [A-Z, a-z, and 0-9].

Input Format

The first line contains space-separated integers $N$ (rows) and $\mbox{M}$ (columns) respectively. 

The next $N$ lines contain the row elements of the matrix script. 

Constraints  

$0<N,M<100$  

Note: A $\mbox{o}$ score will be awarded for using 'if' conditions in your code.

Output Format

Print the decoded matrix script.

Sample Input 0
7 3
Tsi
h%x
i #
sM 
$a 
#t%
ir!

Sample Output 0
This is Matrix#  %!

Explanation 0

The decoded script is:

This$#is% Matrix#  %!

Neo replaces the symbols or spaces between two alphanumeric characters with a single space     ' ' for better readability.

So, the final decoded script is:

This is Matrix#  %!

Source: hackerrank | Difficulty: MEDIUM_HARD


Solutions:
import re
(m, n) = list(map(int, input().split()))
pattern = '([A-Za-z0-9]){1}[^A-Za-z0-9]{1,}([A-Za-z0-9]){1}'
a = list()
for row in range(m):
	a.append(input())
message = []
for col in range(n):
	for row in range(m):
		message.append(a[row][col])
mystring = ''.join(message)
mystring2 = re.sub(pattern, '\\g<1> \\g<2>', mystring)
print(mystring2)


import re
__author__ = 'namii'
L = []
(rows, cols) = map(int, input().rstrip().split())
for i in range(rows):
	L.append(input().strip('\n'))
word = ''
for i in range(cols):
	word += ''.join((j[i] for j in L))
patterni = '[A-Za-z0-9]+'
garbages = re.split(patterni, word)
alkuosat = re.findall(patterni, word)
alku = ' '.join(alkuosat)
len(garbages) != 0 and print(garbages[0], end='')
print(alku, end='')
len(garbages) > 1 and print(garbages[-1], end='')


import re
(n, m) = [int(i) for i in input().split()]
matrix = []
for _ in range(n):
	line = input()
	matrix.append(line)
text = ''.join([''.join([matrix[j][i] for j in range(n)]) for i in range(m)])
the_match = re.compile('[0-9A-Za-z]([^0-9A-Za-z]{2,}|[^0-9A-Za-z ])[0-9A-Za-z]').search(text)
while the_match:
	text = text[:the_match.start() + 1] + ' ' + text[the_match.end() - 1:]
	the_match = re.compile('[0-9A-Za-z]([^0-9A-Za-z]{2,}|[^0-9A-Za-z ])[0-9A-Za-z]').search(text)
print(text)


import re
(n, m) = list(map(int, input().split()))
specsChars = set(('!', '@', '#', '$', '%', '&', ' '))
neo = []
res = [''] * m
firStr = ''
finStr = ''
for i in range(n):
	neo.append(input())
	for j in range(m):
		res[j] += neo[i][j]
res = ''.join(res)
while res != '' and res[-1] in specsChars:
	finStr = res[-1] + finStr
	res = res[:-1]
	pass
while res != '' and res[0] in specsChars:
	firStr += res[0]
	res = res[1:]
	pass
res = re.sub('[\\!|@|#|\\$|%|&]', ' ', res)
res = ' '.join(res.split())
print(firStr + res + finStr)


import re
(N, M) = tuple(map(int, input().split()))
iMatrix = [list(input())[:M] for i in range(N)]
rawString = ''.join([''.join([iMatrix[r][c] for r in range(N)]) for c in range(M)])
moreReadable = re.sub('(?<=[a-zA-Z0-9])[!@#$%& ]+(?=[a-zA-Z0-9])', ' ', rawString)
print(moreReadable)


import re
(rows, columns) = map(int, input().split())
matrix = []
for i in range(rows):
	matrix.append(list(input()))
decode = ''
for i in range(columns):
	word = ''
	for j in range(rows):
		word += matrix[j][i]
	decode += word
print(re.sub('(?<=[\\w])[\\W]+(?=[\\w]+)', ' ', decode))


import re
parts = input().split()
n = int(parts[0])
m = int(parts[1])
a = ['' for i in range(m)]
for row in range(1, n + 1):
	line = input()
	for col in range(0, m):
		a[col] = a[col] + line[col]
ret = ''.join(a)
ret = re.sub('([A-Za-z0-9])[^A-Za-z0-9]+([A-Za-z0-9])', lambda l: l.group(1) + ' ' + l.group(2), ret)
print(ret)


import re
(N, M) = map(int, input().split())
L = []
for _ in range(N):
	S = input()
	L.append(list(S))
SL = ''
for _ in zip(*L):
	SL = SL + ''.join(_)

def replaceMatrixCode(match):
	return match.group(0).replace(match.group(1), ' ')
r = re.sub('[a-zA-Z0-9]([!@#$%&\\s]+)[a-zA-Z0-9]', replaceMatrixCode, SL)
print(r)


import re
(N, M) = map(int, input().split())
pat = '(?<=\\w)([\\W\\s]+)(?=\\w)'
text = [[] for x in range(M)]
for i in range(N):
	row = input()
	for j in range(M):
		text[j].append(row[j])
n_text = ''
for row in text:
	for char in row:
		n_text += char
processed = re.sub(pat, ' ', n_text)
print(processed)


import re
(n, m) = input().strip().split(' ')
(n, m) = [int(n), int(m)]
matrix = []
for _ in range(n):
	matrix_t = str(input())
	matrix.append(matrix_t)
complete = ''
for el in zip(*matrix):
	complete += ''.join(el)
print(re.sub('(?<=\\w)([^\\w]+)(?=\\w)', ' ', complete))


import re
(r, c) = map(int, input().split())
arr = []
for _ in range(r):
	arr.append(input())
string = ''.join([''.join(z) for z in zip(*arr)])
reg = '[!|@|#|\\$|\\%|&|\\s]+'
word = re.sub(reg, ' ', string)
start = ''.join(re.findall('^[!|@|#|\\$|\\%|&|\\s]+', string))
end = ''.join(re.findall('[!|@|#|\\$|\\%|&|\\s]+$', string[len(start):]))
print(start + word.strip() + end)


import re
(n, m) = map(int, input().split())
lines = []
for _ in range(m):
	lines.append('')
for _ in range(n):
	for (i, c) in enumerate(input()[:m]):
		lines[i] += c
line = ''.join(lines)
print(re.sub('(?<=[a-z\\d])[ !@#$%&]+(?=[a-z\\d])', ' ', line, flags=re.I))


from string import *

def main():
	(n, m) = map(int, input().split())
	l = []
	for _ in range(n):
		l.append(input())
	s = ''
	for j in range(m):
		for i in range(n):
			s += l[i][j]
	symbols = '!@#$%& '
	first_dic = {c: 1000 for c in symbols}
	start = 1000
	for i in range(len(s)):
		start = min(start, first_dic.get(s[i], i))
	start = {1000: 0}.get(start, start)
	pre = s[:start]
	last_dic = {c: -1 for c in symbols}
	last = -1
	for i in range(len(s)):
		last = max(last, last_dic.get(s[i], i))
	suf = s[last + 1:]
	d = {str(i): str(i) for i in list(range(10)) + list(ascii_lowercase) + list(ascii_uppercase)}
	new_s = ''
	for i in s[start:last + 1]:
		new_s += d.get(i, ' ')
	print(pre + ' '.join(''.join(new_s).split()) + suf)
main()


import re
(N, M) = tuple(map(int, input().split()))
x = ''
s = ''
for i in range(N):
	x += input().strip('\n').strip('\r')
for j in range(M):
	for i in range(N):
		s += x[i * M + j]
ss = re.sub('(?<=\\w)([\\s!@#$%&]+)(?=\\w)', ' ', s)
print(ss)


def func(s):
	return ord(s) >= 65 and ord(s) <= 90 or (ord(s) >= 97 and ord(s) <= 122) or (ord(s) >= 48 and ord(s) <= 57)
(n, m) = input().split()
n = int(n)
m = int(m)
ar = []
st = []
points = int(0)
for i in range(0, n):
	str = list(input())
	ar.append(str)
for i in range(0, n):
	for j in range(0, m):
		ar[i][j] = ar[i][j]
for j in range(0, m):
	for i in range(0, n):
		st.append(ar[i][j])
		points = points + 1
i = 0
j = 0
while j < m * n:
	i = i
	j = j
	while j < m * n and (not func(st[j])) and (not func(st[i])) and (i == 0):
		j = j + 1
	while j < m * n and (not func(st[j])) and (not func(st[i])) and (i != 0):
		print(st[j], end='')
		j = j + 1
	while j < m * n and func(st[j]) and (not func(st[i])) and (i == 0):
		while i < j:
			print(st[i], end='')
			i = i + 1
	while j < m * n and func(st[j]):
		i = j
		print(st[j], end='')
		j = j + 1
	while j < m * n and (not func(st[j])) and func(st[i]):
		j = j + 1
	while j >= m * n and i < j - 1 and func(st[i]):
		while i < j - 1:
			i = i + 1
			print(st[i], end='')
	while j >= m * n and i < j - 1 and (i == 0) and (not func(st[i])):
		while i < j:
			print(st[i], end='')
			i = i + 1
	print(' ', end='')


import operator
import re
from functools import reduce
(n, m) = list(map(int, input().split()))
a = [[c for c in input()] for i in range(n)]
s = ''.join(reduce(operator.__add__, zip(*a)))
chars = ' !@#\\$%&'
matches = re.findall('(?:^[%s]*)*[a-zA-Z-0-9]+(?:[%s]*$)*|[%s]+$' % ((chars,) * 3), s)
print(' '.join(matches))


from re import sub as res
(n, m) = map(int, input().split())
a = [input().replace('\r', '') for i in range(n)]
inp = ''
for i in range(m):
	for j in range(n):
		inp += a[j][i]
print(res('(?<=[a-zA-Z0-9])[ !@#$%&]+(?=[a-zA-Z0-9])', ' ', inp))


import re
(Row, Col) = list(map(int, input().split()))
Matrix = [[0 for x in range(Col)] for y in range(Row)]
for i in range(Row):
	Matrix[i] = list(input())
L = ''
for j in range(Col):
	for i in range(Row):
		L = L + Matrix[i][j]
(L1, L2) = re.search('(^.*[A-Za-z0-9]|)(?=([^A-Za-z0-9]*$))', L).group(1, 2)
print(re.sub('(?<=\\w)\\W+(?=\\w)', ' ', L1) + L2)


import re
(n, m) = list(map(int, input().split()))
character_ar = [''] * (n * m)
for i in range(n):
	line = input()
	for j in range(m):
		character_ar[i + j * n] = line[j]
decoded_str = ''.join(character_ar)
final_decoded_str = re.sub('(?<=[A-Za-z0-9])([ !@#$%&]+)(?=[A-Za-z0-9])', ' ', decoded_str)
print(final_decoded_str)


print(__import__('re').sub('(?<=\\w)\\W+(?=\\w)', ' ', ''.join(map(''.join, zip(*(input() for _ in range(int(input().split()[0]))))))))


import re
(n, m) = map(lambda x: int(x), input().split())
lines = [input().rstrip('\r') for i in range(n)]
line = ''
for i in range(m):
	for j in range(n):
		line += lines[j][i]

def smth(m):
	return m.group(0)[0] + ' '
line = re.sub('[A-Za-z0-9]([!@#$%&\\s]+)(?=[A-Za-z0-9])', smth, line)
print(line)


import re
(n, m) = map(int, input().split())
mat = []
s = ''
for _ in range(n):
	mat.append(input())
s = ''.join([''.join(a) for a in zip(*mat)])
symbols = '!@#$%&'
s = re.sub('(?<=\\w)([' + symbols + '\\s]+)(?=\\w)', ' ', s)
print(s)


import re
(N, M) = map(int, input().split())
s = ''.join([''.join(x) for x in zip(*[input() for x in range(N)])])
print(re.sub('(?<=[A-Za-z0-9])([\\W_]+)(?=[A-Za-z0-9])', ' ', s))


import sys
import re
(K, M) = map(int, sys.stdin.readline().split())
lines = [sys.stdin.readline().rstrip('\n') for _ in range(K)]
encoded = ''.join((''.join(l) for l in zip(*lines)))

def re_sub(m):
	return m.group(1) + ' ' + m.group(2)
print(re.sub('([A-Za-z0-9])[^A-Za-z0-9]+([A-Za-z0-9])', re_sub, encoded))


import re
(n, m) = map(int, input().split())
data = [input() for _ in range(n)]
s = ''.join((data[i][j] for j in range(m) for i in range(n)))
alnum = '[A-Za-z0-9]'
print(re.sub('(?<=' + alnum + ')[ !@#$%&]+(?=' + alnum + ')', ' ', s))


from functools import reduce
from operator import add
import re
(N, M) = map(int, input().split())
l = list(zip(*(input() for i in range(N))))
s = ''
for v in l:
	s += ''.join((val for val in v))
print(re.sub('(?<=[a-zA-Z0-9])[^a-zA-Z0-9]+(?=[a-zA-Z0-9])', ' ', s))


import re
REPLACE_REGEX = re.compile('(?<=[A-Za-z0-9])[!@#$%& ]+(?=[A-Za-z0-9])')

def parse_nb_rows_columns(s):
	return map(int, s.split())

def get_lines(nb_lines):
	for _ in range(nb_lines):
		yield input()

def decode_lines(nb_columns, lines):
	for i in range(nb_columns):
		for line in lines:
			yield line[i]

def replace_with_space(s):
	return REPLACE_REGEX.sub(' ', s)

def main():
	(nb_rows, nb_columns) = parse_nb_rows_columns(input())
	lines = list(get_lines(nb_rows))
	decoded = ''.join(decode_lines(nb_columns, lines))
	print(replace_with_space(decoded))
main()


import re
print(re.sub('(?<=\\w)[ !@#$%&]+(?=\\w)', ' ', ''.join([''.join(x) for x in zip(*[input().strip('\r\n') for _ in range(int(input().split()[0]))])])))


(n, m) = map(int, input().split())
s = []
for i in range(0, n):
	x = input()
	s.append(x)
z = ''
for j in range(0, m):
	for i in range(0, n):
		z += s[i][j]
n = len(z)
y = 0
k = 0
while bool(z[k] == '!' or z[k] == '@' or z[k] == '#' or (z[k] == '$') or (z[k] == '%') or (z[k] == '&') or (z[k] == ' ')):
	print(z[k], sep='', end='')
	k += 1
r = n - 1
c = 0
while bool(z[r] == '!' or z[r] == '@' or z[r] == '#' or (z[r] == '$') or (z[r] == '%') or (z[r] == '&') or (z[r] == ' ')):
	r -= 1
	c += 1
for i in range(k, n - c):
	x = 2 * int(bool(z[i] == '!' or z[i] == '@' or z[i] == '#' or (z[i] == '$') or (z[i] == '%') or (z[i] == '&') or (z[i] == ' ')))
	y = bool(y == 0 and x == 2)
	x += int(bool(y == 1))
	y = int(bool(z[i] == '!' or z[i] == '@' or z[i] == '#' or (z[i] == '$') or (z[i] == '%') or (z[i] == '&') or (z[i] == ' ')))
	print(x == 3 and ' ' or '', sep='', end='')
	x = bool('a' <= z[i] <= 'z' or 'A' <= z[i] <= 'Z')
	print(x == 1 and z[i] or '', sep='', end='')
r += 1
while r < n:
	print(z[r], sep='', end='')
	r += 1


import re
(N, M) = map(int, input().split())
s = ''.join([''.join(t) for t in zip(*[input().rstrip('\r') for _ in range(N)])])
print(re.sub('(?<=[A-Za-z\\d])[\\!@#\\$%& ]+(?=[A-Za-z\\d])', ' ', s))


import re
(n, m) = (int(i) for i in input().split())
rubbish = re.compile('(?<=[a-zA-Z0-9])[^a-zA-Z0-9]+(?=[a-zA-Z0-9])')
matrix = []
for _ in range(m):
	matrix.append('')
for _ in range(n):
	row = input()
	for i in range(m):
		matrix[i] += row[i]
linetrix = ''.join(matrix)
linetrix = rubbish.sub(' ', linetrix)
print(linetrix)


import re
(n, m) = [int(x) for x in input().split()]
s = []
for _ in range(n):
	s.append([x for x in input()])
t = ''.join([str(y) for x in zip(*s) for y in x])
print(re.sub('(?<=[a-zA-Z0-9])([!@#$%& ]+)(?=[a-zA-Z0-9])', ' ', ''.join([str(y) for x in zip(*s) for y in x])))


import re
(n, m) = map(int, input().split())
encrypted = ''
decrypted = ''
for _ in range(n):
	encrypted += input().strip('\r')
decrypted = ''.join(list([encrypted[x::m] for x in range(m)]))
print(re.sub('([a-zA-Z0-9])[!%#@$& ]+([a-zA-Z0-9])', '\\1 \\2', decrypted))


(n, m) = map(int, input().split())
matrix = []
for _ in range(n):
	matrix.append(list(input()))
l = list(zip(*matrix))
t = [item for sublist in l for item in sublist]
msg = ''.join(t)
import re

def dashrepl(matchobj):
	return matchobj.group(1) + ' '
	return '%s %s' % (matchobj.group(1), matchobj.group(3))
ptn = '([a-zA-Z0-9]{1,})([!@#$%&\\s]+)(?=([a-zA-Z0-9]{2,}))'
msg = re.sub(ptn, dashrepl, msg)
print(msg.replace('##', ' '))


def isChar(x):
	return 'a' <= x <= 'z' or 'A' <= x <= 'Z' or '0' <= x <= '9'

def solve():
	(N, M) = tuple(map(int, input().split()))
	a = []
	for i in range(N):
		a.append(list(input()))
	p = 'a'
	for i in range(M):
		for j in range(N):
			p = p + a[j][i]
	curr = N * M
	while not isChar(p[curr]):
		curr -= 1
	while curr == 0:
		return p[1:]
	(p, alpha) = (p[1:curr + 1], p[curr + 1:])
	ans = ''
	beta = ''
	i = 0
	while not isChar(p[i]):
		beta = beta + p[i]
		i += 1
	while True:
		try:
			while isChar(p[i]):
				ans += p[i]
				i += 1
		except:
			return beta + ans + alpha
		try:
			while not isChar(p[i]):
				i += 1
		except:
			return beta + ans + alpha
		ans += ' '
print(solve())


import re
(n, m) = map(int, input().split())
l = []
for i in range(n):
	l.append(input())
s = ''
for j in range(m):
	for i in range(n):
		s += l[i][j]
print(re.sub('([a-zA-Z0-9])(?:\\$|!|@|#|%|&| )+([a-zA-Z0-9])', '\\g<1> \\g<2>', s))


import re
(n, m) = input().split()
n = int(n)
m = int(m)
matrix = []
for i in range(n):
	matrix.append(input())
mstring = ''
for i in range(m):
	for j in range(n):
		mstring += matrix[j][i]
mstring = re.sub('(?<=[a-zA-Z0-9])([^a-zA-Z0-9]+)(?=[a-zA-Z0-9])', ' ', mstring)
print(mstring)


from re import *
(N, M) = input().split()
N = int(N)
M = int(M)
matNM = []
for _ in range(N):
	m = [x for x in input().strip('\r')]
	matNM.append(m)
	transposemat = list(zip(*matNM))
phrase = ''
for item in transposemat:
	for indivchar in item:
		phrase += indivchar
newphrase = sub('(?<=[a-zA-Z0-9])([^a-zA-Z0-9_]+)(?=[a-zA-Z0-9])', ' ', phrase)
print(newphrase)


import re
(n, m) = map(int, input().split())
script = []
text = ''
for i in range(n):
	script.append(list(input().strip('\r')))
for col in range(m):
	for row in range(n):
		text += script[row][col]
print(re.sub('(?<=\\w)([!@$#% ]+)(?=\\w)', ' ', text))


import re

def decode_matrix(encoded_matrix, rows, columns):
	message = ''
	for i in range(columns):
		for j in range(rows):
			message += encoded_matrix[j][i]
	return message

def format_message(decoded_message):
	ALPHA = '[a-zA-Z0-9]'
	NON_ALPHA = '[\\s!@#$%&]+'
	return re.sub('({}){}({})'.format(ALPHA, NON_ALPHA, ALPHA), '\\g<1> \\g<2>', decoded_message)
(N, M) = [int(x) for x in input().split()]
encoded_matrix = [input().strip('\r\n') for i in range(N)]
decoded_message = decode_matrix(encoded_matrix, N, M)
message = format_message(decoded_message)
print(message)


import re
(N, M) = map(int, input().split())
lines = [input() for _ in range(N)]
text = ''.join([''.join(l) for l in list(zip(*lines))])
print(re.sub('(?<=[a-zA-Z0-9])[^a-zA-Z0-9]+(?=[a-zA-Z0-9])', ' ', text))


import re
(N, M) = map(int, input().strip().split(' '))
arr = []
for _ in range(N):
	arr.append(input().replace('\n', ''))
txt = ''
for m in range(M):
	for n in range(N):
		txt += arr[n][m]
txt = re.sub('(\\w)([!@#$%& ]+)(\\w)', '\\1 \\3', txt)
print(txt)


import re
(m, n) = tuple(map(int, input().split()))
a = []
for i in range(m):
	a.append(list(input().rstrip('\n')))
s = ''
for i in range(n):
	for j in range(m):
		s += a[j][i]
p = re.compile('([a-zA-z0-9][\\$\\#\\!\\@\\ \\%\\&]{1,99}[a-zA-Z0-9])')
matches = list(map(lambda x: x[1:-1], re.findall(p, s)))
b = s[:]
for i in matches:
	b = b.replace(i, ' ', 1)
print(b)


import sys
import re
p = re.compile('(?<=\\w)([\\$\\#\\%\\s]+)(?=\\w)')
dem = sys.stdin.readline().split()
r = int(dem[0])
c = int(dem[1])
rows = [l for l in sys.stdin]
text = ''
for i in range(c):
	for j in range(r):
		text = text + rows[j][i]
print(p.sub(' ', text))


import re
(N, M) = map(int, input().split())
L = list()
for _ in range(M):
	L.append(list())
for _ in range(N):
	x = input()[:M]
	for (i, s) in enumerate(x):
		L[i].append(s)
S = ''.join([''.join(x) for x in L])
print(re.sub('(?<=[\\w])([\\W]+)(?=[\\w])', ' ', S))


import string
(rows, cols) = tuple(map(int, input().split(' ')))
m = []
for i in range(rows):
	m.append(input())
s = ''
for y in range(cols):
	for x in range(rows):
		s += m[x][y]
res = ''
alphanumerical = string.ascii_letters + '0123456789'
while len(s) > 0 and s[0] not in alphanumerical:
	res += s[0]
	s = s[1:]
while len(s) > 0:
	while len(s) > 0 and s[0] in alphanumerical:
		res += s[0]
		s = s[1:]
	g = ''
	while len(s) > 0 and s[0] not in alphanumerical:
		g += s[0]
		s = s[1:]
	while len(s) == 0:
		res += g
		break
	while len(s) > 0:
		res += ' '
		break
print(res)


(m, n) = tuple(map(int, input().split()))
mat = [list(input()) for i in range(m)]
tmp = ''.join(map(lambda x: ''.join(x), list(map(list, zip(*mat)))))
(f, l) = ([], [])
i = 0
while i < len(tmp) and (not tmp[i].isalnum()):
	f.append(tmp[i])
	i += 1
i = 0
while i < len(tmp) and (not tmp[len(tmp) - 1 - i].isalnum()):
	l.append(tmp[len(tmp) - 1 - i])
	i += 1
f = ''.join(f)
l = ''.join(reversed(l))
import re
x = ' '.join(filter(lambda x: len(x) > 0, re.split('(?:\\@|\\!|\\#|\\&|\\%|\\$|\\s)\\s*', tmp)))
while f == l and x == '':
	f = ''
print(f + x + l)


import re
[y, x] = map(int, input().split())
matrix = []
for i in range(y):
	matrix.append(input())
s = ''
for i in range(x):
	for j in range(y):
		s += matrix[j][i]
output = re.sub('(?<=\\w)[ !@#$%&]+(?=\\w)', ' ', s)
print(output)


import re
import itertools
(n, m) = (int(x) for x in input().split())
matrix = [input() for _ in range(n)]
decoded = ''.join(itertools.chain.from_iterable(zip(*matrix)))
decoded = re.sub('(?<=[A-Za-z0-9])[^A-Za-z0-9]+(?=[A-Za-z0-9])', ' ', decoded)
print(decoded)


import itertools
import string
import sys

def decode(data):
	res = []
	for i in range(len(data[0])):
		for j in range(len(data)):
			res.append(data[j][i])
	groups = [list(grp) for (key, grp) in itertools.groupby(res, key=lambda v: v in string.ascii_letters)]
	for i in range(1 + (not groups[0][0] in string.ascii_letters), len(groups) - (not groups[-1][0] in string.ascii_letters), 2):
		groups[i] = [' ']
	return ''.join([''.join(s) for s in groups])
data = [item.strip('\n\r') for item in sys.stdin.readlines()[1:]]
print(decode(data))


import re
(r, c) = map(int, input().split())
matrix = list(zip(*[input() for _ in range(r)]))
string = ''
for t in matrix:
	string = string + ''.join(t)
print(re.sub('\\b[!@#$%&\\s]+\\b', ' ', string))


import operator
import itertools
import functools

def read_f(f):
	return f(input())

def read_f_words(f):
	return map(f, input().split())

def transpose(s):
	out = []
	for ci in range(len(s[0])):
		line = ''
		for ri in range(len(s)):
			try:
				line += s[ri][ci]
			except:
				line += ' '
		out.append(line)
	return out

def mconcat(s):
	return functools.reduce(lambda acc, s: acc + s, s)

def span(f, s):
	lhs = list(itertools.takewhile(f, s))
	rhs = s[len(lhs):]
	return (''.join(lhs), ''.join(rhs))

def clean(s0):
	(lead, s1) = span(lambda x: x in '!@#$%& ', s0)
	(endr, s2) = span(lambda x: x in '!@#$%& ', s1[::-1])
	end = endr[::-1]
	s3 = s2[::-1]
	for c in '!@#$%&':
		s3 = s3.replace(c, ' ')
	ws = itertools.filterfalse(lambda x: x == '', s3.split(' '))
	s4 = ' '.join(ws)
	return lead + s4 + end
(rows, cols) = read_f_words(int)
matrix = []
for r in range(rows):
	matrix.append(input()[0:cols])
print(clean(mconcat(transpose(matrix))))


import re
(m, n) = map(int, input().split())
matrix = [input() for _ in range(m)]
script = ''.join((''.join(row[::-1]) for row in zip(*matrix[::-1])))
print(re.subn('(\\w)([ !@#$%&]+)(\\w)', '\\1 \\3', script)[0])


import re
(n, m) = map(int, input().split())
a = [input() for _ in range(n)]
s = ''.join([''.join([x[i] for x in a]) for i in range(m)])
print(re.sub('(?<=\\w)\\W+(?=\\w)', ' ', s))


import re
(n, m) = map(int, input().split())
l = [0 for i in range(n * m)]
for i in range(n):
	s = input()
	for j in range(m):
		l[n * j + i] = s[j]
s = ''.join(l)
s = re.sub('([A-Za-z0-9])([^A-Za-z0-9])+([A-Za-z0-9])', '\\1 \\3', s)
print(s)


import re
(rows, cols) = map(int, input().split())
mat = {}
res = ''
notisalpha = lambda x: x.isalpha()
for i in range(rows):
	mat[i] = list(input())
for i in range(cols):
	for j in range(rows):
		res += mat[j][i]
regex = re.compile('(?<=[\\w\\d])[^A-Za-z0-9]+(?=[\\w\\d]+)+')
res = regex.sub(' ', res)
res = res.split()
res = ' '.join(res)
print(res)


def decodeMatrix(matrix):
	n = len(matrix)
	m = len(matrix[0])
	r1 = ''
	for j in range(m):
		for i in range(n):
			r1 += matrix[i][j]
	r2 = ''
	keep = []
	for i in range(26):
		keep.append(chr(ord('a') + i))
		keep.append(chr(ord('A') + i))
	for i in range(10):
		keep.append(chr(ord('0') + i))
	head = ''
	remove = ''.join(list(filter(lambda x: x not in keep, r1)))
	jump = sum((r1[:x] == remove[:x] for x in range(1, len(remove) + 1)))
	head = r1[:jump]
	r1 = r1[jump:]
	rest = ''.join(list(filter(lambda x: x in keep, r1)))
	last = ''
	while rest:
		same = sum((r1[:x] == rest[:x] for x in range(1, len(rest) + 1)))
		r2 += r1[:same] + ' '
		r1 = r1[same:]
		remove = ''.join(list(filter(lambda x: x not in keep, r1)))
		jump = sum((r1[:x] == remove[:x] for x in range(1, len(remove) + 1)))
		last = r1[:jump]
		r1 = r1[jump:]
		rest = ''.join(list(filter(lambda x: x in keep, r1)))
	r2 = r2[:-1]
	return head + r2 + last
(n, m) = [int(x) for x in input().strip().split(' ')]
matrix = [''] * n
for i in range(n):
	temp = input()
	matrix[i] = [' '] * m
	for j in range(min(m, len(temp))):
		matrix[i][j] = temp[j]
s = decodeMatrix(matrix)
print(s)


import re
import sys
f = sys.stdin
(N, M) = (int(i) for i in f.readline().split())
matrix = [list(f.readline()) for i in range(N)]
s = ''
for j in range(M):
	for i in range(N):
		s += matrix[i][j]
print(re.sub('(?<=[a-zA-Z0-9])[^a-zA-Z0-9]+(?=[a-zA-Z0-9])', ' ', s))


import re
info = input().split()
rows = int(info[0])
cols = int(info[1])
input_array = []
for row in range(rows):
	input_array.append(list(input()))
input_str = ''.join((''.join(x) for x in zip(*input_array)))
print(re.sub('(\\w+)\\W+(?=\\w+)', '\\1 ', input_str))


import re
(n_rows, m) = (int(x) for x in input().split())
rows = (input() for i in range(n_rows))
txt = ''.join((''.join(row) for row in zip(*rows)))
res = re.sub('([A-Za-z0-9])([^A-Za-z0-9]+)([A-Za-z0-9])', '\\1 \\3', txt)
print(res)


import re
(N, M) = map(int, input().split())
m = []
for _ in range(N):
	m.append(input()[:M])
r = re.compile('([A-Za-z0-9])([^A-Za-z0-9]+)([A-Za-z0-9])')
print(r.sub('\\1 \\3', ''.join([m[j][i] for i in range(M) for j in range(N)])))


import re
input_list = input().split(' ')
n = int(input_list[0])
m = int(input_list[1])
matrix = []
for _ in range(n):
	matrix.append(str(input()))
line = ''
for i in range(m):
	for j in range(n):
		line += matrix[j][i]
results = re.findall('[A-Za-z0-9][!@#$%& ]+[A-Za-z0-9]', line)
for result in results:
	line = line.replace(result, result[0] + ' ' + result[-1])
print(line)


import re
E = re.compile('([\\dA-z])[^A-z\\d]+([\\dA-z])')
(N, M) = [int(x) for x in input().split()]
J = ''.join([input().rstrip('\r') for i in range(N)])
S = ''.join([J[j * M + i] for i in range(M) for j in range(N)])
D = re.sub(E, '\\1 \\2', S)
print(D)


import itertools
import re
(m, n) = list(map(int, input().split()))
l = [input()[:n] for _ in range(m)]
s = ''.join([i for sub in list(itertools.zip_longest(*l, fillvalue=' ')) for i in sub])
match = re.match('^([%!@#&$\\s]*)([\\w]+[%!@#&$\\w\\s]*[\\w]+)([%!@#&$\\s]*)', s)
try:

	def repl(matchobj):
		return ' '
	sub = re.sub('[%!@#&$ ]+', repl, match.group(2))
	sub = str(match.group(1) + re.sub('  ', ' ', sub) + match.group(3))
	print(sub)
except Exception:
	print(s)


import re
(n, m) = map(int, input().split())
a = [input() for _ in range(n)]
s = ''
for i in range(m):
	for j in range(n):
		s = s + a[j][i]
print(re.sub('(?<=[a-zA-Z0-9])[^a-zA-Z0-9]+(?=[a-zA-Z0-9])', ' ', s))


import re

def decode(n, m, s):
	a = ''
	for i in range(m):
		for j in range(n):
			a = a + s[j][i]
	return re.sub('([A-Za-z0-9])[ !@#$%&]+([A-Za-z0-9])', '\\1 \\2', a)
(n, m) = [int(x) for x in input().split(' ')]
a = []
for i in range(n):
	a.append(input())
print(decode(n, m, a))


import re
matrix = list(map(int, input('').split(' ')))
code = []
for x in range(0, matrix[0]):
	code.append(input(''))
decode = ''
for x in range(0, matrix[1]):
	for y in range(0, matrix[0]):
		decode += code[y][x]
print(re.sub('(?<=\\w)\\W+(?=\\w)', ' ', decode))


import re
s = input()
(n, m) = [int(e) for e in s.split(' ')]
data = []
for _ in range(n):
	data.append(list('{0:<3}'.format(input())))
s = ''.join([data[i][j] for j in range(m) for i in range(n)])
res = re.sub('(?<=\\w)\\W+(?=\\w)', ' ', s)
print(res)


import re
from string import ascii_letters, digits
(N, M) = map(int, input().strip().split())
replchr = re.compile('(?<=[a-zA-Z0-9])[^a-zA-Z0-9]{1,}(?=.*[a-zA-Z0-9]+)')
mess = list('0' * N * M)
for k in range(N):
	s = input()
	for l in range(M):
		mess[l * N + k] = s[l]
mess = ''.join((str(x) for x in mess))
print(replchr.sub(' ', mess))


import re
(N, M) = map(int, input().split())
l = list()
for each in range(N):
	s = input().strip('\r\n')
	for j in range(len(s)):
		l.append(s[j])
st = str()
for i in range(M):
	for j in range(N):
		st += l[j * M + i]
print(re.sub('(?<=[A-z0-9])[^A-z0-9]+(?=[A-z0-9])', ' ', st))


import re
(a, b) = map(int, input().split())
l = (input() for i in range(a))
s = ''.join((''.join(a) for a in zip(*l)))
l = 'a-zA-Z0-9'
print(re.sub('([{0}])[^{1}]+([{2}])'.format(l, l, l), '\\1 \\2', s))


import re
(n, m) = map(int, input().split())
s = []
s2 = []
for _ in range(n):
	s.append(input().strip('\n'))
for j in range(m):
	s2.append(''.join([s[i][j] for i in range(n)]))
s2 = ''.join(s2)
p = '(?<=\\w)\\W+(?=\\w)'
s3 = re.sub(p, ' ', s2)
print(s3)


import re
(n, m) = map(int, input().split())
strList = list()
for _ in range(m):
	strList.append(list())
for _ in range(n):
	s = input()
	for i in range(m):
		strList[i] += s[i]
for i in range(m):
	strList[i] = ''.join(strList[i])
s = ''.join(strList)
for found in reversed(re.findall('\\w([ !@#$%&]+)\\w', s, re.A)):
	s = s.replace(found, ' ', 1)
print(s)


import re
(N, M) = map(int, input().split())
matrix = []
for _ in range(N):
	matrix.append(input())
text = ''.join((''.join((matrix[i][j] for i in range(N))) for j in range(M)))
ans = re.sub('(?<=[a-zA-Z0-9])([^a-zA-Z0-9]+)(?=[a-zA-Z0-9])', ' ', text)
print(ans)


import re
(n, m) = list(map(int, input().split(' ')))
data = [input().replace('\r', '') for i in range(n)]
message = ''.join([datum[col] for col in range(m) for datum in data])
print(re.sub('(?<=[a-zA-Z0-9])([\\!\\@\\#\\$\\%\\&\\ ]+)(?=[a-zA-Z0-9])', ' ', message))


import re
compress_reg = re.compile('([a-zA-Z0-9])[ !@#$%&]+([a-zA-Z0-9])')
(ns, ms) = input().split(' ')
N = int(ns)
M = int(ms)
cols = [[] for _ in range(M)]
for _ in range(N):
	row = input()
	for i in range(M):
		cols[i].append(row[i])
sentence = ''.join(sum(cols, []))
print(compress_reg.sub('\\1 \\2', sentence))


import re
(M, N) = map(int, input().split())
enc = [input() for _ in range(M)]
dec = ''.join([i[j] for j in range(N) for i in enc])
print(re.sub('(?<=[a-z\\d])[^a-z\\d]+(?=[a-z\\d])', ' ', dec, flags=re.I))


import re
line1 = input().split()
n = int(line1[0])
m = int(line1[1])
matrix = []
for i in range(0, n):
	matrix.append([])
	for c in input():
		matrix[i].append(c)
script = ''
for i in range(0, m):
	for j in range(0, n):
		script += matrix[j][i]
for m in re.finditer('[A-Za-z0-9]([!@#\\$%& ]+)[A-Za-z0-9]', script):
	script = script.replace(m.group(1), ' ', 1)
print(script)


from string import *

def main():
	d = {}
	for i in range(10):
		d[str(i)] = str(i)
	for c in ascii_lowercase:
		d[c] = c
	for c in ascii_uppercase:
		d[c] = c
	d[' '] = ' '
	(n, m) = map(int, input().split())
	l = []
	for _ in range(n):
		l.append(input())
	s = ''
	for j in range(m):
		for i in range(n):
			s += l[i][j]
	ddd = {'!': -1, '@': -1, '#': -1, '$': -1, '%': -1, '&': -1, ' ': -1}
	las = -1
	for i in range(len(s)):
		no = ddd.get(s[i], i)
		las = max(las, no)
	suf = s[las + 1:]
	kkk = {'!': 1000, '@': 1000, '#': 1000, '$': 1000, '%': 1000, '&': 1000, ' ': 1000}
	st = 1000
	for i in range(len(s)):
		no = kkk.get(s[i], i)
		st = min(st, no)
	abc = {1000: 0}
	st = abc.get(st, st)
	pre = s[:st]
	new_s = ''
	for i in s[st:las + 1]:
		new_s += d.get(i, ' ')
	print(pre + ' '.join(''.join(new_s).split()) + suf)
main()


import re
(n, m) = list(map(int, input().split(' ')))
transposedMatrix = [list('-' * n) for _ in range(m)]
for rowI in range(n):
	col = input()
	for colI in range(m):
		transposedMatrix[colI][rowI] = col[colI]
decodedMatrix = ''.join([''.join(row) for row in transposedMatrix])
print(re.sub('([A-Za-z0-9]+)([!@#$%& ]+)(?=[A-Za-z0-9]+)', '\\1 ', decodedMatrix))


import re
(n, m) = [int(i) for i in input().strip().split()]
M = []
for _ in range(n):
	M.append(input()[:m])
A = ''.join([M[j][i] for i in range(m) for j in range(n)])
print(re.sub('(?<=[a-zA-Z0-9])[^a-zA-Z0-9]+(?=[a-zA-Z0-9])', ' ', A))


import re
n = list(map(int, input().split()))
s = [list(input()) for _ in range(n[0])]
s = ''.join([s[y][x] for x in range(n[1]) for y in range(n[0])])
print(re.sub('(?<=\\w)([\\W]+)(?=\\w)', ' ', s))


firstline = input().split(' ')
rows = int(firstline[0])
cols = int(firstline[1])
matrix = [list(input()) for _ in range(rows)]
decoded = ''
for c in range(cols):
	for r in range(rows):
		value = matrix[r][c]
		decoded += value
import re
decoded = re.sub('([a-zA-Z])[^a-zA-Z]+([a-zA-Z])', '\\1 \\2', decoded)
print(decoded)


import re
(n, m) = map(int, input().split())
l = [input() for i in range(n)]
s = ''.join((l[i][j] for j in range(m) for i in range(n)))
print(re.sub('(?<=[a-zA-Z0-9])([^a-zA-Z0-9]+)(?=[a-zA-Z0-9])', ' ', s))


import re
(N, M) = map(int, input().split())
print(re.sub('(?<=[A-Za-z0-9])[^A-Za-z0-9]+(?=[A-Za-z0-9])', ' ', ''.join((''.join(map(str, _)) for _ in zip(*tuple((input() for _ in range(N))))))))


import re
(n, m) = map(int, input().split())
matrix = [input()[:m] for _ in range(n)]
script = ''.join((''.join(l) for l in map(list, zip(*matrix))))
regex_for_symbols = re.compile('(?<=[a-zA-Z0-9])([!@#$%& ]+)(?=[a-zA-Z0-9]+)')
decoded_script = regex_for_symbols.sub(' ', script)
print(decoded_script)


import re

def repl(match):
	return match.group(1) + ' ' + match.group(3)
(n, m) = map(int, input().strip().split())
res = ['' for _ in range(n * m)]
for i in range(n):
	s = list(input())
	for k in range(m):
		idx = k * n + i
		res[idx] = s[k]
res = ''.join((x for x in res))
print(re.sub('(\\w)([^a-zA-Z0-9]+)(\\w)', repl, res))


import re
(r, c) = map(int, input().split())
ls = []
for i in range(r):
	ls.append(list(input()))
us = list(zip(*ls))
vs = ''.join([''.join(u) for u in us])
sp = re.compile('(?<=[a-zA-Z0-9])[!@#\\$%& ]+(?=[a-zA-Z0-9])')
rs = sp.sub(' ', vs)
print(rs)


import sys
stdin = sys.stdin
(n, m) = map(int, stdin.readline().split())
s = [' '] * (n * m)
for i in range(n):
	line = stdin.readline().rstrip()
	for j in range(len(line)):
		s[j * n + i] = line[j]
s = ''.join(s)
import re
print(re.sub('(?<=\\w)\\W+(?=\\w)', ' ', s))


import re
(n, m) = map(int, input().split())
mat = [input() for _ in range(n)]
st = ''
for i in range(m):
	for j in range(n):
		st += mat[j][i]
print(re.sub('(?<=\\w)\\W+(?=\\w)', ' ', st))


import re
(N, M) = input().split()
mat = []
for i in range(int(N)):
	mat.append(input())
matz = list(zip(*mat))
meg = ''.join([let for i in matz for let in i])
print(re.sub('(?<=\\w)\\W+(?=\\w)', ' ', meg))


import re
(n, m) = list(map(int, input().split(' ')))
s = list(range(n * m))
for i in range(n):
	s[i::n] = list(input()[:m])
print(re.sub('(?<=[a-z0-9])([\\s!@#$%&]+)(?=[a-z0-9])', lambda x: ' ', ''.join(s), flags=re.I))


import re
(N, M) = map(int, input().split())
columns = list()
for m in range(M):
	columns.append(list())
for n in range(N):
	row = input()
	for m in range(M):
		columns[m].append(row[m])
decoded = str()
for column in columns:
	decoded += ''.join(column)
print(re.sub('(?<=([0-9A-Za-z]))\\W+(?=([0-9A-Za-z]))', ' ', decoded))


import re
(R, C) = map(int, input().split())
theMatrixLOL = [list(input()) for _ in range(R)]
decoded = ''
for j in range(C):
	for i in range(R):
		decoded += theMatrixLOL[i][j]
print(re.sub('(?<=[a-zA-Z0-9])[\\s!@#$%&]+(?=[a-zA-Z0-9])', ' ', decoded))