Removing multiple spaces from a string

is there any way to remove all repeating occurrences of blanks and keep only the single one?
i.e. “_ I_am___ a___Knime____user__” -> “I_am_a_Knime_user”

One way you could to this is to use some of the replace functions available in the String Manipulation node.

Very interesting suggestion…! Do you really think I posted the question without trying anything before?

As presented your string appears to have no multiple spaces, but to have spaces at the start and end. To solve the problem you asked, I would use a Java Snippet node configured to replace your incoming column:

String str = c_MyColumnReferenceHere.trim();  //Incoming column
while (str.contains("  ")){  //2 spaces
    str = str.replace("  ", " "); //(2 spaces, 1 space)
c_resultColumn = str; //Result column


1 Like

Hi Steve, it works!!! Thank you so much!

Hi Alfroc,
I once had the same problem and did a (very overkilling) Recursive Loop for it.

So I would go for Steves Solution here.

Cheers, Iris

PS: If you think a solution solves your question you can marked it as solution, this is hidden under the three dots below the post. And than the checkbox.

1 Like

Thanks @Iris - I did think of using a recursive loop too!


@Iris what do you think of making it a function in the String Manipulation node?

Here is interesting discussion how to do it in SQL. Possibly, same could be done in KNIME.

Even though the problem has been solved. I would recommend to use a regular expression for these types of replacements. This way you can remove an arbitary amount of whitespaces.
Use this in a String Manipulation Node and it should solve the problem nicely: strip(regexReplace($column1$,"\\s{2,}" ," "))
The \\s stands for whitespaces and the {2,} means two or more.


Thank you for your contribution @MH , it’s a very elegant solution!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.