Stripe leading, trailing and more than 1 space from String
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 space characters at the beginning / end of the line.
The hard part is a pattern \s+(?=\s)
that matches one or more whitespace characters followed by another whitespace character that does not itself count as part of a match ("forward-looking statement").
Typically \s
matches all space characters, such as the space character itself, horizontal tab, newline, carriage return, line feed, or formatting. If you only want to remove (duplicate) whitespace characters, then replace the pattern with
let pattern = "^ +| +$| +(?= )"
source to share
You can keep the regex simple by doing the leading / trailing part as the second step:
let singlySpaced = " Simple text with spaces "
.stringByReplacingOccurrencesOfString("\\s+", withString: " ", options: .RegularExpressionSearch)
.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
(assuming you want to remove all kinds of spaces - you can adjust it to just make just spaces)
There are more complex regexprs out there that will do this in one shot, but personally I prefer the two-step version over obfuscation (and as @MartinR mentions, the performance is very similar to the two, given that trimming is a very light operation against a slower more complex regex - so which is indeed the case to which you prefer the look).
source to share
This should clear your lines:
var string : NSString = " hello world. "
while string.rangeOfString(" ").location != NSNotFound { //note the use of two spaces
string = string.stringByReplacingOccurrencesOfString(" ", withString: " ")
}
println(string)
string = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
println(string)
source to share
Some good answers have been provided, but if you want a regex, then the following should work:
^ |(?<= ) +| $
|
indicates alternatives, ^
- start of line, character $
indicates end of line. So it matches the start of a line, followed by a space OR one or more spaces, followed by a space OR a space at the end of the line.
source to share