let us = "http://example.com"
let range = us.rangeOfString("(?<=://)[^.]+(?=.com)", options:.RegularExpressionSearch)
if range != nil {
let found = us.substringWithRange(range!)
print("found: \(found)") // found: example
}
This code extracts substring
between backslashes and dot com in Swift 2. I searched Internet and I found that rangeOfString
changed to range()
.
But still I could not make the code work in Swift 3.0. Could you help me ?
edit : I'm using swift 3 07-25 build.
Returns a range of consecutive characters from string, starting with the character whose index is first and ending with the character whose index is last. An index of 0 refers to the first character of the string.
Ranges in Swift allow us to select parts of Strings, collections, and other types. They're the Swift variant of NSRange which we know from Objective-C although they're not exactly the same in usage, as I'll explain in this blog post. Ranges allow us to write elegant Swift code by making use of the range operator.
In Swift, a range is a series of values between two numeric intervals. For example, var numbers = 1... 4. Here, ... is a range operator.
In swift 3.0 rangeOfString
syntax changed like this.
let us = "http://example.com"
let range = us.range(of:"(?<=://)[^.]+(?=.com)", options:.regularExpression)
if range != nil {
let found = us.substring(with: range!)
print("found: \(found)") // found: example
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With