I have string:
Simple text with spaces
I need regular expression which select:
Example:
_ - space
_Simple text __with ___spaces_
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.
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.
String result = str. trim(); The trim() method will remove both leading and trailing whitespace from a string and return the result.
The STRIP function is similar to the TRIM function. It removes both the leading and trailing spaces from a character 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 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 = "^ +| +$| +(?= )"
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