user9557173
user9557173

Reputation:

Swift: Search for String inside String and get Index

How can I search for a String and get an Index where I can produce for example a new String/Substring with e.g:

dfnaseurewruTESTAB=41201243

so that in this example I can search for TESTAB and produce a new String:

TESTAB=41201243

Upvotes: 0

Views: 437

Answers (2)

Quoc Nguyen
Quoc Nguyen

Reputation: 3007

You can using Regular Expression for find your TESTAB=number string

Regular Expression can be TESTAB=[\d]+

with TESTAB is your string, = to find the number after and [\d]+ is has one or more number

For example, in Swift 4.1

let regex = "TESTAB=[\\d]+"
let string = "dfnaseurewruTESTAB=41201243"
if let range = string.range(of: regex, options: .regularExpression, range: nil, locale: nil) {
    print(string[range]) // result is TESTAB=41201243
}

Upvotes: 1

matt
matt

Reputation: 534885

You can't really do it in pure Swift, which (amazingly) lacks the ability to search for substrings. You have to operate in the presence of Foundation; that way, you can use Cocoa's range(of:). The result is translated from an NSRange back into a Swift Range for you (wrapped in an Optional in case the substring isn't present at all). The lower bound of the range is the index you're looking for — the start of the substring.

let s = "dfnaseurewruTESTAB=41201243"
if let r = s.range(of: "TESTAB") {
    let s2 = s.suffix(from: r.lowerBound)
    print(s2) // "TESTAB=41201243"
}

Upvotes: 1

Related Questions