How to match anything other than a space and a new line?

I have a line, I just want to match a line for any character except a space and a new line. What should a regular expression be for?

I know regular expressions for anything other than space, that is, [^ ]+ and regular expressions for anything other than the new line [^\n]+ (I'm on Windows). I cannot figure out how to combine them together.

+7
python regex
source share
2 answers

You can add a space character to your character class, which will be excluded.

 ^[^\n ]*$ 

Regular expression

 ^ # the beginning of the string [^\n ]* # any character except: '\n' (newline), ' ' (0 or more times) $ # before an optional \n, and the end of the string 
+5
source share

If you want to exclude only space and newlines, then you can 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 

Please note that it will not eliminate all other space characters, such as tabs, line characters, etc.

 print re.match(r'^[^ \n]*$', """Welcome\ttoStackoverflow""") # <_sre.SRE_Match object at 0x7f77a2a58238> 

So, if you want to exclude all whitespace, 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 matches [^\s] . Quoting from documents,

\ s

If the UNICODE flag is not specified, it matches any space character, this is equivalent to the set [ \t\n\r\f\v] . The LOCALE flag does not have an additional effect on space mapping. If UNICODE set, this will match the characters [ \t\n\r\f\v] plus everything that is classified as a space in the Unicode character property database.

\ S

If UNICODE flags are not specified, they match any character without spaces; this is equivalent to the set [^ \t\n\r\f\v] The LOCALE flag does not have an additional effect on matching without spaces. If UNICODE is specified, then any character that is not marked as a space in the Unicode character property database is mapped.

+2
source share

All Articles