0

I have got a string range in Swift but I want to extend it on by a few characters but I cannot see how to do this.

Here is my code:

var fullMessage = "This\n is\n my example\n message.\n Thanks Leigh Smith\n and some more characters\n and lots more \n"
var startName = fullMessage.rangeOfString("Leigh")
var endMessage = fullMessage[advance(startName!.endIndex,0)...advance(fullMessage.endIndex,-1)]

var posRange = endMessage.rangeOfString("\n")
var pos = posRange?.startIndex
var xpos = advance(startName!.endIndex, 0)

fullMessage = fullMessage[advance(fullMessage.startIndex, 0)...advance(startName!.endIndex,advance(pos, 0))]

My problem is that fullMessage could contain random numbers of \n. I want to get the string from the start of the fullMessage string until the \n after "Leigh" i.e. "This\n is\n my example\n message.\n Thanks Leigh Smith\n".

My thoughts were to find the next "\n" and then extend the original range. Hopefully there is an easy way of doing this with much nicer code.

Thanks

macaaw

iphaaw
  • 6,764
  • 11
  • 58
  • 83
  • I would choose [Regular expression & matches extraction](http://stackoverflow.com/a/27880748/581190). – zrzka Jul 15 '15 at 21:44

1 Answers1

1
import Foundation

let fullMessage = "This\n is\n my example\n message.\n Thanks Leigh Smith\n and some more characters\n and lots more \n"

extension String {
  func sliceAfter(after: String, to: String) -> String {
    return rangeOfString(after).flatMap {
      rangeOfString(to, range: $0.endIndex..<endIndex).map {
        substringToIndex($0.endIndex)
      }
    } ?? self
  }
}

fullMessage.sliceAfter("Leigh", to: "\n") // "This\n is\n my example\n message.\n Thanks Leigh Smith\n"
oisdk
  • 9,763
  • 4
  • 18
  • 36
  • Thank you. I don't claim to understand it yet but it does seem to work well and was much more concise than the version I finally came up with. You are obviously a Swift string ninja! – iphaaw Jul 27 '15 at 18:15