Removing White Spaces From Data in Spark

There are multiple methods provided by the spark to handle white spaces in data. The most basic way to remove white spaces is to use “regexp_replace”. Unfortunately “regexp_replace” is not always easy to use. So we are going to learn some simple functions like trim, ltrim & rtrim to remove white spaces.

ltrim

We can use ltrim to remove white spaces from beginning of string.

rtrim

Just like ltrim, we can use rtrim to remove trailing white spaces from string.

trim

If we want to remove white spaces from both ends of string we can use the trim function.

We can easily check if this is working or not by using length function.

Removing White Spaces using Trim
Removing White Spaces using Trim

Using “regexp_replace” to remove white spaces

“regexp_replace” is powerful & multipurpose method. Let us see how we can use it to remove white spaces around string data in spark.

Obviously this regular expression removes all white space from a string. even space between words. By changing regular expression, you can use the above code for multiple use cases.

I hope you found this useful. See you in next blog 🙂

Similar Posts

Leave a Reply

Your email address will not be published.