If you want to exclude just space and newline characters, then you might want to use
r'^[^ \n]*$'
For example,
print re.match(r'^[^ \n]*$', """WelcometoStackoverflow""")
# <_sre.SRE_Match object at 0x7f77a2a58238>
print re.match(r'^[^ \n]*$', """Welcome toStackoverflow""")
# None
print re.match(r'^[^ \n]*$', """Welcome
toStackoverflow""")
# None
Note that it will not eliminate all the other whitespace characters, like tabs, line feed characters etc
print re.match(r'^[^ \n]*$', """Welcome\ttoStackoverflow""")
# <_sre.SRE_Match object at 0x7f77a2a58238>
So if you want to exclude all the whitespace characters then you can use
r'^[^\s]*$'
Or
r'^\S*$'
For example,
print re.match(r'^[^\s]*$', """WelcometoStackoverflow""")
# <_sre.SRE_Match object at 0x7f9146c8b238>
print re.match(r'^[^\s]*$', """Welcome toStackoverflow""")
# None
print re.match(r'^[^\s]*$', """Welcome
toStackoverflow""")
# None
print re.match(r'^[^\s]*$', """Welcome\ttoStackoverflow""")
# None
\S
is the same as [^\s]
. Quoting from the docs,
\s
When the UNICODE
flag is not specified, it matches any whitespace character, this is equivalent to the set [ \t\n\r\f\v]
. The LOCALE
flag has no extra effect on matching of the space. If UNICODE
is set, this will match the characters [ \t\n\r\f\v]
plus whatever is classified as space in the Unicode character properties database.
\S
When the UNICODE
flags is not specified, matches any non-whitespace character; this is equivalent to the set [^ \t\n\r\f\v]
The LOCALE
flag has no extra effect on non-whitespace match. If UNICODE
is set, then any character not marked as space in the Unicode character properties database is matched.