4

I'm making a method in Kotlin using Regex that checks if a string contains one or more of certain pronouns (such as "I", "we", "you", etc). E.g. "We are a tech company" should be a match, "Web is for spiders" should not be a match.

I tried with this code:

fun main() {
    val text = "We are testing!"
    val regex = "/\b(i|you|we)\b/g".toRegex()
    if (regex.containsMatchIn(text.lowercase())) {
        println("match")
    } else {
        println("no match")
    }
}

, but it prints "no match".

olamatre
  • 61
  • 2
  • 6

1 Answers1

6

Kotlin (and Java) regexps are defined with string literals, and not regex literals, i.e. when you add / at the start and /g (or just /) at the end of the pattern, you actually add them to the pattern string.

You can use the following fix:

val text = "We are testing!"
val regex = """(?i)\b(i|you|we)\b""".toRegex()
if (regex.containsMatchIn(text)) {
    println("match")
} else {
    println("no match")
}

The """(?i)\b(i|you|we)\b""" is equal to "(?i)\\b(i|you|we)\\b", the former treats backslashes as literal chars.

Note you do not need to use .lowercase(), the (?i) case insensitive modifier will make matching case insensitive.

See the online Kotlin demo.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563