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
*/