components由Swift中的多个分隔符分隔

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (37)

所以这是字符串s

"Hi! How are you? I'm fine. It is 6 p.m. Thank you! That's it."

我希望它们被分隔为一个数组:

["Hi", "How are you", "I'm fine", "It is 6 p.m", "Thank you", "That's it"]

这意味着分隔符应为". "+ "? "+"! "

我试过了:

let charSet = NSCharacterSet(charactersInString: ".?!")
let array = s.componentsSeparatedByCharactersInSet(charSet)

但它也将分为p.m.两个元素。结果:

["Hi", " How are you", " I'm fine", " It is 6 p", "m", " Thank you", " That's it"]

我也试过了

let array = s.componentsSeparatedByString(". ")

它可以很好地用于分离". ",但如果我也想分开"? ""! ",它变得杂乱。

所以我能做到这一点吗?谢谢!

提问于
用户回答回答于

提供了一种允许枚举字符串的方法。您可以通过单词或句子或其他选项来完成此操作。不需要正则表达式。

let s = "Hi! How are you? I'm fine. It is 6 p.m. Thank you! That's it."
var sentences = [String]()
s.enumerateSubstringsInRange(s.startIndex..<s.endIndex, options: .BySentences) { 
    substring, substringRange, enclosingRange, stop in
    sentences.append(substring!)
}
print(sentences)

结果是:

["Hi! ", "How are you? ", "I\'m fine. ", "It is 6 p.m. ", "Thank you! ", "That\'s it."]

用户回答回答于

我试图找到一个正则表达式来解决这个问题:(([^.!?]+\s)*\S+(\.|!|\?)) 这里是regexper的解释和一个例子

扫码关注云+社区

领取腾讯云代金券