【发布时间】:2015-08-03 02:12:27
【问题描述】:
我有字符串:
Simple text with spaces
我需要选择的正则表达式:
- 领先
- 尾随
- 超过 1 个空格
例子:
_ - space
_Simple text __with ___spaces_
【问题讨论】:
-
请正确解释问题。
标签: ios regex string swift nsregularexpression
我有字符串:
Simple text with spaces
我需要选择的正则表达式:
例子:
_ - space
_Simple text __with ___spaces_
【问题讨论】:
标签: ios regex string swift nsregularexpression
我的 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+ 和 \s+$ 匹配字符串开头/结尾处的一个或多个空白字符。
棘手的部分是\s+(?=\s) 模式,它匹配一个或多个
空白字符后跟另一个空白字符,该空白字符本身不考虑
匹配的一部分(“前瞻断言”)。
通常,\s 匹配所有空白字符,例如空格字符本身、水平制表符、换行符、回车符、换行符或换页符。如果
您只想删除(重复的)空格字符,然后将模式替换为
let pattern = "^ +| +$| +(?= )"
【讨论】:
\s 匹配空格、制表符、换行符或换页符。如果您只想匹配空间我们实际的空间
您可以通过将前导/尾随部分作为第二阶段来保持正则表达式的简单:
let singlySpaced = " Simple text with spaces "
.stringByReplacingOccurrencesOfString("\\s+", withString: " ", options: .RegularExpressionSearch)
.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
(假设你想去除所有类型的空格——你可以将其调整为只处理空格)
有更复杂的正则表达式可以一次性完成,但我个人更喜欢两步版本而不是混淆(正如@MartinR 提到的,两者之间的性能非常相似,因为修剪是一个非常轻量级的操作与更慢更复杂的正则表达式相比 - 所以它真的取决于你喜欢的外观)。
【讨论】:
^ | +| $ 一次匹配前导/尾随/不止一件事(如罗伯特的回答所示)很容易。棘手的部分是如果你想删除它,用什么替换它——你想用任何东西替换前导/尾随,但用一个空格替换多个内部空格。
这应该清理你的字符串:
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)
【讨论】:
已经提供了一些很好的答案,但如果你想要一个正则表达式,以下应该可以工作:
^ |(?<= ) +| $
| 表示替代项,^ 是字符串的开头,$ 表示字符串的结尾。所以这匹配字符串的开头后跟一个空格或一个或多个空格,前面有一个空格或字符串末尾的一个空格。
【讨论】:
word __word.
以下将删除所有空格
NSString *spaces =@"hi how are you ";
NSString *withoutSpace= [spaces stringByReplacingOccurrencesOfString:@" "
withString:@" "];
withoutSpace = [withoutSpace stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
【讨论】:
此功能将在单词之间留一个空格
let accountNameStr = " test test "
let trimmed = accountNameStr.replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression)
let textWithoutSpace = trimmed.trimmingCharacters(in: .whitespaces)
输出:测试测试
【讨论】: