返回字符串中第一个和最后一个字符的范围

时间:2016-02-16 21:51:15

标签: ios string swift

我有一个字符串:"Hey @username that's funny"。对于给定的字符串,如何搜索字符串以返回包含第一个字符@和最后一个字符的所有字符串范围以获取username

我想我可以获得@和每个索引的所有索引,得到下一个空格字符的substringToIndex,但想知道是否有更简单的方法。

2 个答案:

答案 0 :(得分:5)

如果您的用户名只能包含字母和数字,则可以使用正则表达式:

let s = "Hey @username123 that's funny"

if let r = s.rangeOfString("@\\w+", options: NSStringCompareOptions.RegularExpressionSearch) {
  let name = s.substringWithRange(r) // @username123"
}

答案 1 :(得分:1)

@ Vladimir的答案是正确的,但是如果你试图找到" username"的多次出现,那么这也应该有效:

    let s = "Hey @username123 that's funny"

    let ranges: [NSRange]

    do {
         // Create the regular expression.
         let regex = try NSRegularExpression(pattern: "@\\w+", options: [])

         // Use the regular expression to get an array of NSTextCheckingResult.
         // Use map to extract the range from each result.
         ranges = regex.matchesInString(s, options: [], range: NSMakeRange(0, s.characters.count)).map {$0.range}
   }
   catch {
         // There was a problem creating the regular expression
         ranges = []
   }

   for range in ranges {

         print((s as NSString).substringWithRange(range))

   }