0

I want to extract a value from a string in swift 4.

I tried to use regular expression but it didn't work all i want is to extract the PK value from this query:

"INSERT INTO table(PK,anotherValue) VALUES ('38061','1233')"

I want the result here to be: 38061

the regex i tried:

   var results = [String]()
    do{
    let regex = try NSRegularExpression(pattern:" VALUES ('(.*?)'", options: [])
    regex.enumerateMatches(in: query, options: [], range: NSMakeRange(0, query.utf16.count)) { result, flags, stop in
        if let r = result?.range(at: 1), let range = Range(r, in: query) {
            results.append(String(query[range]))
        }
    }
    } catch {
       print( error)
    }
    print(results) 

i got below error :

Error Domain=NSCocoaErrorDomain Code=2048 "The value “ VALUES ('(.?)'” is invalid." UserInfo={NSInvalidValue= VALUES ('(.?)'

1 Answer 1

5

The parentheses are special characters for capturing groups.

To treat a parenthesis as literal character you have to escape it:

pattern:" VALUES \\('(.*?)'"

Please look at: https://regex101.com/r/lyzoex/1

Sign up to request clarification or add additional context in comments.

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.