Home > Software engineering >  How to extract content between 2 curly braces using swift macos? [closed]
How to extract content between 2 curly braces using swift macos? [closed]

Time:10-02

i want to extract this content any string content [email protected] any string content

I tried many ways but it still doesn't work properly

Can you all help me extract that content?

let email = "[email protected]"
let content = "{any string content [email protected] any string content} {any string content [email protected] any string content}{any string content [email protected] any string content}"

let regex = try NSRegularExpression(pattern: "\\{(.*)" email "(.*)\\}")
let matches = regex.matches(in: content, range: NSRange(content.startIndex..., in: content))
                            for match in matches {
                                let swiftRange = Range(match.range(at: 1), in: content)!
                                print(content[swiftRange]) //any string content [email protected] any string content} {any string content
}

CodePudding user response:

You said:

i want to extract this content any string content [email protected] any string content

The trouble is that the expression .* matches curly braces, so you are not confining the search to a single matching pair of curly braces. Plus, it is greedy, whereas you want the shortest match so that you stop at the first matching right curly brace. What you want is something more like this:

let email = "[email protected]"
let content = "{any string content [email protected] any string content} {any string content [email protected] any string content}{any string content [email protected] any string content}"

let pattern = "\\{([^{}]*" email ".*?)\\}"
let regex = try NSRegularExpression(pattern: pattern)
if let result = regex.firstMatch(in: content, options: [], range: NSRange(content.startIndex..., in:content)) {
    let range = result.range(at: 1)
    if let srange = Range(range, in:content) {
        print(content[srange])
        // any string content [email protected] any string content
    }
}

As you can see, we got exactly the output you said you wanted. It is possible that what you said you wanted is not what you really wanted, but you should be able to take it from here.

CodePudding user response:

you could just use this:

let arr = content.split(separator: "{").map{String($0.trimmingCharacters(in: .whitespacesAndNewlines).dropLast())}
if let result = arr.first(where: { $0.contains(email) }) {
    print("---> result: \(result)")
}
  • Related