NSRegularExpression 删除空格

发布于 2024-11-16 19:05:41 字数 220 浏览 3 评论 0原文

我需要一点关于 iPhone 上的正则表达式的启动。实际上我正在处理 UITextField.text。如果文本的值为空并且该值已经存在,我可以处理它。但是,如果该值只是空格,我不想使用它。因此,如果该值类似于“”或“文件夹”,我希望该值分别为“”和“文件夹”。

我计划使用 NSRegularExpression 删除空格并浏览文档。但这有点令人困惑。因此,帮助我解决从给定字符串中删除空格的问题。先感谢您。

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 of the problem of removing white space from the given string. Thank you in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

遮云壑 2024-11-23 19:05:41

编辑:您需要修剪字符串,因此不需要正则表达式,只需使用:

[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

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

[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
π浅易 2024-11-23 19:05:41

正则表达式将是:

/\s+/g

然后您将其替换为“”

您如何通过 iOS 语法进行替换我不知道,但这就是全部的正则表达式:)

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 :)

抚笙 2024-11-23 19:05:41

一个更实际的问题是,如何修剪和压缩空白,

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!
}

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!
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文