Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,181 questions

56,073 answers

573 users

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, 2025 by avibootz
...