Home > Mobile >  Parse a space delimited string, except when the space is inside quotations without regex
Parse a space delimited string, except when the space is inside quotations without regex

Time:03-20

There is a duplicate of this question in Go and several that use regex, but I would like to achieve this using Kotlin and without regex. Here's the question:

I was wondering if there is a nice way (without using regex) I could easily split a string at spaces, except when the space is inside quotation marks?

For example, changing

Foo bar random "letters lol" stuff

into

[Foo, bar, random, "letters lol", stuff]

With the following code:

val splitLine = line.split(" ")

The answer comes out to:

[Foo, bar, random, "letters, lol", stuff]

Which is incorrect.

CodePudding user response:

Since you specifically asked for a non-Regex based code, you can do something like this:

val words = mutableListOf<String>()
var lastWord = ""
var quote = false
for (ch in s) {
    if (ch == '"') quote = !quote
    if (ch == ' ' && !quote) {
        words.add(lastWord)
        lastWord = ""
    } else
        lastWord  = ch
}
words.add(lastWord)

Try it yourself

CodePudding user response:

I believe you will need regex here.

val text = "Foo bar random \"letters lol\" stuff"
val regex = Regex("\".*?\"|\\w ")
val matches = regex.findAll(text).map{it.value}.toList()
println(matches)  // [Foo, bar, random, "letters lol", stuff]

The regex pattern used above eagerly tried to first match a doubly quoted term. That failing, it falls back to matching a word.

  • Related