从String中删除前导,尾随和超过1个空格

时间:2015-05-21 12:06:21

标签: ios regex string swift nsregularexpression

我有字符串:

Simple text   with    spaces

我需要选择正则表达式:

  • 导致
  • 超过1个空格

示例:

_ - space

_Simple text __with ___spaces_

6 个答案:

答案 0 :(得分:4)

我的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)模式,它匹配一个或多个 空格字符后跟另一个空白字符,其本身不是 比赛的一部分(&#34;前瞻性断言&#34;)。

通常,\s匹配所有空格字符,例如空格字符本身,水平制表符,换行符,回车符,换行符或换页符。如果 你想只删除(重复的)空格字符,然后用

替换模式
let pattern = "^ +| +$| +(?= )"

答案 1 :(得分:2)

您可以通过将前导/尾随部分作为第二阶段来保持正则表达式的简单:

 let singlySpaced = " Simple text   with    spaces   "
      .stringByReplacingOccurrencesOfString("\\s+", withString: " ", options: .RegularExpressionSearch)
      .stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

(假设您要删除所有类型的空格 - 您可以将其调整为仅相当容易的空格)

有更复杂的正则表达式可以一次性完成,但我个人更喜欢两步版本而不是混淆(并且正如@MartinR所提到的,两者之间的性能非常相似,因为修剪是非常轻量级的操作vs一个更慢,更复杂的正则表达式 - 所以它真的很低,你更喜欢它的外观。

答案 2 :(得分:1)

这应该清理你的琴弦:

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)

答案 3 :(得分:1)

已经提供了一些好的答案,但是如果你想要一个正则表达式,下面应该有效:

^ |(?<= ) +| $

|表示备选方案,^是字符串的开头,$表示字符串的结尾。所以这匹配字符串的开头后跟一个空格或一个或多个空格,前面是空格或字符串末尾的空格。

答案 4 :(得分:0)

以下将删除所有空格

NSString *spaces =@"hi how are you "; 

NSString *withoutSpace= [spaces stringByReplacingOccurrencesOfString:@"  " 
                               withString:@" "];
withoutSpace = [withoutSpace stringByTrimmingCharactersInSet:
                              [NSCharacterSet whitespaceCharacterSet]];

答案 5 :(得分:-1)

此功能会在单词之间留一个空格

let accountNameStr = "   test    test   "
    let trimmed = accountNameStr.replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression)
    let textWithoutSpace = trimmed.trimmingCharacters(in: .whitespaces)

输出:测试测试