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,569 questions

56,787 answers

573 users

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

1 Answer

0 votes
fun extractContentBetweenTags(str: String, tagName: String): String? {
    // Build a regex pattern using the specified tag name
    val pattern = "<$tagName>(.*?)</$tagName>".toRegex()

    // Use regex to find the content
    val match = pattern.find(str)
    
    return match?.groups?.get(1)?.value // Return the content inside the tags or null if no match is found
}

fun main() {
    val str = "abcd <tag>efg hijk lmnop</tag> qrst uvwxyz"

    // Call the function to extract the substring
    val content = extractContentBetweenTags(str, "tag")

    if (content != null && content.isNotEmpty()) {
        println("Extracted content: $content")
    } else {
        println("No matching tags found.")
    }
}

   
      
/*
run:
   
Extracted content: efg hijk lmnop
  
*/

 



answered Apr 3, 2025 by avibootz
...