^(\s+)
only removes the whitespace from the first line. How do I remove the front whitespace from all the lines?
strip() Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.
The replaceAll() method accepts a string and a regular expression replaces the matched characters with the given string. To remove all the white spaces from an input string, invoke the replaceAll() method on it bypassing the above mentioned regular expression and an empty string as inputs.
The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing " " with "".
You can easily trim unnecessary whitespace from the start and the end of a string or the lines in a text file by doing a regex search-and-replace. Search for ^[ \t]+ and replace with nothing to delete leading whitespace (spaces and tabs). Search for [ \t]+$ to trim trailing whitespace.
Python's regex module does not default to multi-line ^
matching, so you need to specify that flag explicitly.
r = re.compile(r"^\s+", re.MULTILINE) r.sub("", "a\n b\n c") # "a\nb\nc" # or without compiling (only possible for Python 2.7+ because the flags option # didn't exist in earlier versions of re.sub) re.sub(r"^\s+", "", "a\n b\n c", flags = re.MULTILINE) # but mind that \s includes newlines: r.sub("", "a\n\n\n\n b\n c") # "a\nb\nc"
It's also possible to include the flag inline to the pattern:
re.sub(r"(?m)^\s+", "", "a\n b\n c")
An easier solution is to avoid regular expressions because the original problem is very simple:
content = 'a\n b\n\n c' stripped_content = ''.join(line.lstrip(' \t') for line in content.splitlines(True)) # stripped_content == 'a\nb\n\nc'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With