How to extract a substring between two tags using RegEx in Swift

1 Answer

0 votes
import Foundation

func extractContentBetweenTags(_ str: String, tagName: String) -> String? {
    // Build a regex pattern using the specified tag name
    let pattern = "<\(tagName)>(.*?)</\(tagName)>"
    
    // Compile the regex
    let regex = try? NSRegularExpression(pattern: pattern)
    
    // Perform the regex search
    if let regex = regex,
       let match = regex.firstMatch(in: str, options: [], range: NSRange(location: 0, length: str.utf16.count)) {
        // Extract the matched content
        if let range = Range(match.range(at: 1), in: str) {
            return String(str[range])
        }
    }
    
    // Return nil if no match is found
    return nil
}

let str = "abcd <tag>efg hijk lmnop</tag> qrst uvwxyz"

// Call the function to extract the substring
if let content = extractContentBetweenTags(str, tagName: "tag") {
    print("Extracted content: \(content)")
} else {
    print("No matching tags found.")
}



/*
run:

Extracted content: efg hijk lmnop

*/

 



answered Apr 3 by avibootz
...