0

I have a huge text in String.

For example "... value=word. ...". How can I get the string "word" if I know that before I have "value=" and after "."?

for example:

for str in string {
    if str == "value=" {
        // then get the strings until .
    }
}

Thanks!

0

4 Answers 4

1

You can extend String with a kind of sliceBetween method:

import Foundation

extension String {
  func sliceFrom(start: String, to: String) -> String? {
    guard let s = rangeOfString(start)?.endIndex else { return nil }
    guard let e = rangeOfString(to, range: s..<endIndex)?.startIndex else { return nil }
    return self[s..<e]
  }
}

And you'd use it like this:

"... value=word. ...".sliceFrom("value=", to: ". ") // "word"
Sign up to request clarification or add additional context in comments.

Comments

1

NSRegularExpression should solve your issue.

In order to use it, you will need to understand Regex first. In your case, you can use value=[\\w]+[^.]+ as your regex pattern.

The following code will give you a [String] object contains value=allCharacterBeforeFirstPeriod

let regex = try NSRegularExpression(pattern: "value=[\\w]+[^.]+", options: [])
let nsStr = str as NSString
let array = regex.matchesInString(str, options: [], range: NSMakeRange(0, nsStr.length))
let results = array.map({ nsStr.substringWithRange($0.range) })

And then if you only need the value after value=, you can use another map function to do it:

results.map({ $0.stringByReplacingOccurrencesOfString("value=", withString: "") })

I have tested the code with a 10,000 characters String. It finishes in ~0.3 sec

Comments

0

The most straight forward way to do this would be to use NSRegularExpression. Tutorial

Comments

0

Given an input String like this

let text = "key0=value0&key1=value1&key2=value2"

You can organireduce method

let dict = text.characters.split("&").reduce([String:String]()) { (var result, keyValue) -> [String:String] in
        let chunks = keyValue.split("=")
        guard let first = chunks.first, last = chunks.last else { return result }
        let key = String(first)
        let value = String(last)
        result[key] = value
        return result
}

Now everything is stored inside dict and you can easily access it

dict["key2"] // "value2"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.