0

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

2 Answers 2

1

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"
}
Sign up to request clarification or add additional context in comments.

Comments

1

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
}

Comments

Your Answer

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