Python RegEx – Match Whitespace But Not Newline

5/5 - (1 vote)

Problem Formulation

πŸ’¬ Challenge: How to design a regular expression pattern that matches whitespace characters such as the empty space ' ' and the tabular character '\t', but not the newline character '\n'?

An example of this would be to replace all whitespaces (except newlines) between a space-delimited file with commas to obtain a CSV.

Method 1: Use Character Class

The character class pattern [ \t] matches one empty space ' ' or a tabular character '\t', but not a newline character. If you want to match an arbitrary number of empty spaces except for newlines, append the plus quantifier to the pattern like so: [ \t]+.

Here’s an example where you replace all separating whitespace (except newline) with a comma to receive a CSV formatted output:

import re

txt = 'a   \t  b        c\nd  e   f'
csv_txt = re.sub('[ \t]+', ',', txt)
print(csv_txt)

Output:

a,b,c
d,e,f

Why the space in the pattern [ \t]?

The reason there’s a space in the pattern is to match the empty space. The character class essentially is an OR relationship, i.e., one item within the character class is matched. For the given pattern, it matches either the empty space ' ' or the tabular character '\t'.

🌍 Learn More: Character Class (Character Set) — The Ultimate Guide for Python

Method 2: Match Individual Different Whitespace Characters

The previous method only matches the horizontal tab (U+0009) and breaking space (U+0020) characters. If you want more fine-grained control about which whitespace characters to match and which not, you can use the following baseline approach.

The following list of Unicode whitespace characters UNICODE_WHITESPACES contains all major whitespace variants you may want to check your string for. You can generate a character class using the string expression '[' + ''.join(UNICODE_WHITESPACES) + ']'.

Here’s a variant that finds all matches of whitespace characters in a given text:

import re

UNICODE_WHITESPACES = [
    "\u0009", # character tabulation
    "\u000a", # line feed
    "\u000b", # line tabulation
    "\u000c", # form feed
    "\u000d", # carriage return
    "\u0020", # space
    "\u0085", # next line
    "\u00a0", # no-break space
    "\u1680", # ogham space mark
    "\u2000", # en quad
    "\u2001", # em quad
    "\u2002", # en space
    "\u2003", # em space
    "\u2004", # three-per-em space
    "\u2005", # four-per-em space
    "\u2006", # six-per-em space
    "\u2007", # figure space
    "\u2008", # punctuation space
    "\u2009", # thin space
    "\u200A", # hair space
    "\u2028", # line separator
    "\u2029", # paragraph separator
    "\u202f", # narrow no-break space
    "\u205f", # medium mathematical space
    "\u3000", # ideographic space
]

txt = ' \t\n\r'
pattern = '[' + ''.join(UNICODE_WHITESPACES) + ']'
matches = re.findall(pattern, txt)
print(matches)
# [' ', '\t', '\n', '\r']

Of course, you can restrict this to only contain whitespaces that are not newline-related.

Method 3: Match Individual Different Whitespaces Except Newlines

The following code snippet uses the UNICODE_WHITESPACES constant but comments out the newline whitespaces so that newline-related characters such as '\n' and '\r' are not matched anymore!

import re

UNICODE_WHITESPACES = [
    "\u0009", # character tabulation
    # "\u000a", # line feed
    "\u000b", # line tabulation
    "\u000c", # form feed
    # "\u000d", # carriage return
    "\u0020", # space
    # "\u0085", # next line
    "\u00a0", # no-break space
    "\u1680", # ogham space mark
    "\u2000", # en quad
    "\u2001", # em quad
    "\u2002", # en space
    "\u2003", # em space
    "\u2004", # three-per-em space
    "\u2005", # four-per-em space
    "\u2006", # six-per-em space
    "\u2007", # figure space
    "\u2008", # punctuation space
    "\u2009", # thin space
    "\u200A", # hair space
    # "\u2028", # line separator
    # "\u2029", # paragraph separator
    "\u202f", # narrow no-break space
    "\u205f", # medium mathematical space
    "\u3000", # ideographic space
]

txt = ' \t\n\r'
pattern = '[' + ''.join(UNICODE_WHITESPACES) + ']'
matches = re.findall(pattern, txt)
print(matches)
# [' ', '\t']

Of course, you can comment out the individual whitespace Unicode characters you don’t want to match as required by your own application.