HackerRank Solution: Tag Content Extractor using Kotlin

This tutorial will shoe you how to solve HackerRank Tag Content Extractor. In a tag-based language like XML or HTML, contents are enclosed between a start tag and an end tag like <tag>contents</tag>. Note that the corresponding end tag starts with a /.

Given a string of text in a tag-based language, parse this text and retrieve the contents enclosed within sequences of well-organized tags meeting the following criterion:

The name of the start and end tags must be same. The HTML code <h1>Hello World</h2> is not valid, because the text starts with an h1 tag and ends with a non-matching h2 tag.

Tags can be nested, but content between nested tags is considered not valid. For example, in <h1><a>contents</a>invalid</h1>, contents is valid but invalid is not valid.

Tags can consist of any printable characters.

Sample Input

<h1>Nayeem loves counseling</h1>
<h1><h1>Sanjay has no watch</h1></h1><par>So wait for a while</par>
<Amee>safat codes like a ninja</amee>
<SA premium>Imtiaz has a secret crush</SA premium>

Sample Output
Nayeem loves counseling
Sanjay has no watch
So wait for a while
None
Imtiaz has a secret crush
Please have a look how to create Kotlin project in Eclipse
The source code

class TagContentExtractor {
	companion object {
		@JvmStatic val ANY_TAG_NAME_REGEX = "<(.+)>([^<]+)</\1>"
		fun extractTagContent(tagContent: String): String {
			val sb = StringBuilder()
			var newLine = ""
			Regex(ANY_TAG_NAME_REGEX).findAll(tagContent).forEach {
				sb.append(newLine)
				sb.append(it.value.replace("\<[^>]*>".toRegex(), ""))
				newLine = "n"
			}
			var result = if (sb.isEmpty()) "None" else sb.toString()
			return result
		}
	}
}
fun main(args: Array<String>) {
	println(TagContentExtractor.extractTagContent("<h1>Nayeem loves counseling</h1>"));
	println(TagContentExtractor.extractTagContent("<h1><h1>Sanjay has no watch</h1></h1><par>So wait for a while</par>"));
	println(TagContentExtractor.extractTagContent("<Amee>safat codes like a ninja</amee>"));
	println(TagContentExtractor.extractTagContent("<SA premium>Imtiaz has a secret crush</SA premium>"));
}

Running the Kotlin program

Do right click on the above Kotlin class and select Run As -> Kotlin Application

Output
Nayeem loves counseling
Sanjay has no watch
So wait for a while
None
Imtiaz has a secret crush
Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *