-2

In Kotlin, i need to find the string value after and before of specific character,

For example,

Item1. myResultValue: someother string

So in the above, I need to get the value after ". " and before ":" SO my output should be "myResultValue". If it doesn't match it can return empty or null value.

Please help to write to Regex for this.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
GK_
  • 1,212
  • 1
  • 12
  • 26
  • 2
    Does this answer your question? [Regular Expression to find a string included between two characters while EXCLUDING the delimiters](https://stackoverflow.com/questions/1454913/regular-expression-to-find-a-string-included-between-two-characters-while-exclud) – aSemy Nov 24 '22 at 05:24
  • Can there be multiple such patterns in the string i.e. multiple `. ` or `:`? What output do you expect in that case? Just the first match or all of them? – Arpit Shukla Nov 24 '22 at 06:53

1 Answers1

1

For your specific case you can use regex:

val text = "Item1. myResultValue: someother string"

val pattern = Pattern.compile(".*\\.(.*):.*")
val matcher = pattern.matcher(text)
if (matcher.matches()) {
    println(matcher.group(1))
}

If you want to build something smarter that defines the start and end pattern you can do it like this:

val startSearch = "\\."
val endSearch = ":"
val text = "Item1. myResultValue: someother string"

val pattern = Pattern.compile(".*$startSearch(.*)$endSearch.*")
val matcher = pattern.matcher(text)
if (matcher.matches()) {
    println(matcher.group(1))
}
Yonatan Karp-Rudin
  • 1,056
  • 8
  • 24