开发者

NSRegularExpression to remove white space

I need a little kickstart on regex on the iPhone. Actually I am dealing with UITextField.text. If the value of the text is empty and if the value already exist, I can able to deal it. But, if the value is simply white spaces, I do not want to use it. So, if the value is like " " or " folder", I want the value to be "" and "folder" respectively.

I planned to use NSRegularExpression to remove the white space and went through the documents. But it was little confusing. So, help me to come out 开发者_C百科of the problem of removing white space from the given string. Thank you in advance.


Edit: you need to trim string, so no regular expression is needed, simply use:

[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];


The regexp would be:

/\s+/g

You would then replace that with ""

How you do that through iOS syntax for the replacement I don't know, but that's the regExp for it all :)


A more practical question is, How to trim and condense white-spaces,

let text: String? = "  I    don't  know  you !  " // expected result: "I don't know you!"
let charSet = NSCharacterSet.whitespaceAndNewlineCharacterSet()
if let trimmedText = text?.componentsSeparatedByCharactersInSet(charSet).filter({!$0.isEmpty}).joinWithSeparator(" ") {
    print(trimmedText) // I don't know you!
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜