Yann
Yann

Reputation: 135

Kotlin regexp matching parenthesis content

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.

Upvotes: 2

Views: 1999

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626803

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.

Upvotes: 1

Related Questions