Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strip leading, trailing and more than 1 space from String

I have string:

Simple text   with    spaces

I need regular expression which select:

  • leading
  • trailing
  • more than 1 space

Example:

_ - space

_Simple text __with ___spaces_
like image 205
Artem Krachulov Avatar asked May 21 '15 12:05

Artem Krachulov


People also ask

How do you cut leading and trailing spaces from a string?

To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.

How do I remove multiple spaces from a string?

Using sting split() and join() You can also use the string split() and join() functions to remove multiple spaces from a string. We get the same result as above. Note that the string split() function splits the string at whitespace characters by default.

How do you remove trailing spaces from a string?

String result = str. trim(); The trim() method will remove both leading and trailing whitespace from a string and return the result.

Which of the following removes all leading and trailing spaces from a string?

The STRIP function is similar to the TRIM function. It removes both the leading and trailing spaces from a character string.


1 Answers

My 2ct:

let text = "    Simple text   with    spaces    "
let pattern = "^\\s+|\\s+$|\\s+(?=\\s)"
let trimmed = text.stringByReplacingOccurrencesOfString(pattern, withString: "", options: .RegularExpressionSearch)
println(">\(trimmed)<") // >Simple text with spaces<

^\s+ and \s+$ match one or more white space characters at the start/end of the string.

The tricky part is the \s+(?=\s) pattern, which matches one or more white space characters followed by another white space character which itself is not considered part of the match (a "look-ahead assertion").

Generally, \s matches all white-space characters such as the space character itself, horizontal tabulation, newline, carriage-return, linefeed or formfeed. If you want to remove only the (repeated) space characters then replace the pattern by

let pattern = "^ +| +$| +(?= )"
like image 86
Martin R Avatar answered Oct 13 '22 00:10

Martin R