Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to match anything except space and new line using Python regular expression?
Python's re module provides various tools for pattern matching using regular expressions (regex). With the help of regex, we can define flexible patterns that match or exclude particular characters or sequences. In this article, we will focus on how to match everything except spaces and newlines using regular expressions.
The following are the methods involved to match the regex pattern, except for space and new line.
- Using re.findall() Method
- Using re.split() Method
- Replace Spaces and Newlines with Empty String
Match Words Without Space/Newline Using re.findall()
Instead of checking the full string, sometimes we may want to extract all parts of the text that don't contain a space or newline. In such cases, we can use the re.findall() method along with the pattern r'[^ \n]+' to find all continuous sequences that don't contain a space or newline.
Example
The following program demonstrates extracting all substrings that avoid spaces or newlines by using the re.findall() method.
import re text = "I find\nTutorialspoint useful" matches = re.findall(r'[^ \n]+', text) print(matches)
Following is the output of the above code:
['I', 'find', 'Tutorialspoint', 'useful']
Using re.split() to Separate Words by Space/Newline
The re.split() method is used to split a string into a list of substrings based on a specified pattern. When used with a pattern that matches spaces and newlines (r'\s+'), it effectively splits a string into individual words, treating sequences of spaces and newlines as delimiters.
Example
In the following program, [ \n]+ means split wherever one or more spaces/newlines occur. Here we separated the words by space/newline using the re.split() method.
import re data = "Python is\ngreat for regex" parts = re.split(r'[ \n]+', data) print(parts)
Following is the output of the above code:
['Python', 'is', 'great', 'for', 'regex']
Replace Spaces and Newlines with Empty String
If we want to remove all spaces and newlines from a string, then instead of matching, we can replace them with an empty string by using the re.sub() method.
The re.sub() method of the re module in Python, used for regular expressions that replace parts of a string that match a pattern with a specified replacement string.
Example
Here, we use [ \n] pattern and remove all spaces/newlines using '' (empty string).
import re text = "This\nhas some text \n with spaces" clean = re.sub(r'[ \n]', '', text) print(clean)
Following is the output of the above code:
Thhassometextwithspaces