0

I've the below code that is answering the where are you regex, this could be w r u and so.

I I entered how r u, the regex will understand it as w r u, which is not correct in real, how to fix it?

val regEx = """((where|were|w)\s*(are|r)\s*(you|u)(?-i))""".toRegex()

fun main(args: Array<String>) {

    val matchResult = regEx.find("how r u")
    println("Hello, world!: ${matchResult?.value.orEmpty()}")
}
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Hasan A Yousef
  • 22,789
  • 24
  • 132
  • 203
  • What is the expected output for `how r u`? – Zoe Mar 30 '18 at 09:55
  • If it is not correct so what is the correct form? You didn't consider word *how* in your regex. – revo Mar 30 '18 at 09:55
  • Possible duplicate of [Regex match entire words only](https://stackoverflow.com/questions/1751301/regex-match-entire-words-only) – revo Mar 30 '18 at 10:02

1 Answers1

0

Option 1

(^|\s+)

You can use the beginning of line ^ char to achieve a better matcher. If you combine it with a whitespace matcher like this (^|\s+) you make sure you only get the words (where|were|w)

(^|\s+)(where|were|w)\s*(are|r)\s*(you|u)(?-i)

or

(^|\s+)(where|were|w)\s*(are|r)\s*(you|u)\s+(?-i)

see https://regex101.com/r/xyjrO4/1

Option 2

\b

Use the word boundary \b see java regex boundaries

\b(where|were|w)\s*(are|r)\s*(you|u)(?-i)

taking it to the full extend would be

\b(where|were|w)\b\s*\b(are|r)\b\s*\b(you|u)\b(?-i)

(which wouldnt match "wru" though)

Or

((where|were|\bw)\s*(are|r)\s*(you|u)(?-i))
Hasan A Yousef
  • 22,789
  • 24
  • 132
  • 203
leonardkraemer
  • 6,573
  • 1
  • 31
  • 54