2

I'm trying to match parenthesis content using Kotlin.

I found that regex should be /\(([^)]+)\)/ but can't have it working in Kotlin.

val pattern = """/\(([^)]+)\)/""".toRegex(RegexOption.LITERAL)

val text = "aaaa (ferf ) veffef (frr) refef"

fun main() {
    println(pattern.matches(text))
}

returns false.

1
  • Solved my issue thanks a lot Commented Dec 5, 2019 at 21:59

1 Answer 1

1

You need to remove the initial and trailing slashes as you need to define the regex pattern using a string literal, and you need to only capture any chars other than parentheses inside parentheses and use findAll rather than matches to find all matches.

Use

val m = """\(([^()]*)\)""".toRegex()
val text = "aaaa (ferf ) veffef (frr) refef" 
val results =  m.findAll(text).map{it.groupValues[1]}.toList()
println(results)

See the Kotlin demo.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.