Home > OS >  how to extract an integer range from a string
how to extract an integer range from a string

Time:08-10

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.

CodePudding user response:

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)

CodePudding user response:

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…)

  • Related