Abdul Alsabbagh
Abdul Alsabbagh

Reputation: 37

how to extract an integer range from a string

I have a string that contains different ranges and I need to find their value

var str = "some text x = 1..14, y = 2..4 some text" I used the substringBefore() and substringAfter() methodes to get the x and y but I can't find a way to get the values because the numbers could be one or two digits or even negative numbers.

Upvotes: 0

Views: 319

Answers (3)

Semyon Tikhonenko
Semyon Tikhonenko

Reputation: 4242

Using KotlinSpirit library

val rangeParser = object : Grammar<IntRange>() {
    private var first: Int = -1
    private var last: Int = -1

    override val result: IntRange
        get() = first..last

    override fun defineRule(): Rule<*> {
        return int {
            first = it
        } + ".." + int {
            last = it
        }
    }
}.toRule().compile()

val str = "some text x = 1..14, y = 2..4 some text"
val ranges = rangeParser.findAll(str)

https://github.com/tiksem/KotlinSpirit

Upvotes: 0

Desmond
Desmond

Reputation: 203

Is this solution fit for you?

val str = "some text x = 1..14, y = 2..4 some text"    
val result = str.replace(",", "").split(" ")
var x = ""; var y = ""

for (i in 0..result.count()-1) {
    if (result[i] == "x") {
        x = result[i+2]
    } else if (result[i] == "y") {
        y = result[i+2]
    }
}

println(x)
println(y)

Upvotes: 0

gidds
gidds

Reputation: 18547

One approach is to use a regex, e.g.:

val str = "some text x = 1..14, y = 2..4 some text"

val match = Regex("x = (-?\\d+[.][.]-?\\d+).* y = (-?\\d+[.][.]-?\\d+)")
            .find(str)
if (match != null)
    println("x=${match.groupValues[1]}, y=${match.groupValues[2]}")
    // prints: x=1..14, y=2..4

\\d matches a single digit, so \\d+ matches one or more digits; -? matches an optional minus sign; [.] matches a dot; and () marks a group that you can then retrieve from the groupValues property. (groupValues[0] is the whole match, so the individual values start from index 1.)

You could easily add extra parens to pull out each number separately, instead of whole ranges.

(You may or may not find this as readable or maintainable as string-manipulation approaches…)

Upvotes: 2

Related Questions