Ho Binh
Ho Binh

Reputation: 439

Extract numbers from a string kotlin

String.replaceAll is not running and is unsupported in Kotlin. So I suggest a demo example, I hope it help.

var string = "vsdhfnmsdbvfuf121535435aewr"  
string.replace("[^0-9]".toRegex(), "")

Upvotes: 41

Views: 49557

Answers (10)

Semyon Tikhonenko
Semyon Tikhonenko

Reputation: 4242

Using https://github.com/tiksem/KotlinSpirit library

string.replaceAll(int, "")

Upvotes: 0

Juan Martinez
Juan Martinez

Reputation: 121

if you looking for take out the numbers here is the solution

var string = "vsdhfnmsdbvfuf121535435aewr"
var result = string.filter { it.isLetter() }

instead of .isdigit type .isletter and it should work fine

Upvotes: 3

Mohd Qasim
Mohd Qasim

Reputation: 1010

Try this we will get result

val digit:Int = Regex("[^0-9]").replace(bindAyatSearch.ayatSearchSp.selectedItem.toString(), "").toInt()

Upvotes: 0

Prasad
Prasad

Reputation: 3562

For some cases like if the text contains formatted amount, then the above answers might fail. For example, if the text is "Rs. 1,00,000.00" and if we only filter . and digit, then the output we get is .100000.00 this will be a wrong amount. So better first extract the string between digits and then filter for digit and Dot.

    fun String.getAmount(): String {
    return substring(indexOfFirst { it.isDigit() }, indexOfLast { it.isDigit() } + 1)
        .filter { it.isDigit() || it == '.' }
    }

Following cases will be covered using above code

  println("Rs. 123".getAmount())
  println("Rs. 123.23".getAmount())
  println("Rs. 123.23/-".getAmount())
  println("INR123.23".getAmount())
  println("123.23INR".getAmount())
  println("$100,000.00".getAmount())
  println("Rs.100,000.00".getAmount())

Upvotes: 4

Muhammad Mubeen
Muhammad Mubeen

Reputation: 153

Try this example:

Code

  try {
        val p = Pattern.compile("\\d+")
        var m = p.matcher("string1234more567string890")
         while (m.find()) {
           System.out.println(m.group())
          }
      }catch (ex:java.lang.Exception){
      }

Upvotes: 0

The replace function does not modify your string, but it return a new string. Your code will be fine:

  • val result = replace("[^0-9]".toRegex(), "")

Upvotes: 1

jj.
jj.

Reputation: 2390

You could also take advantage of Kotlin's String.filter:

var string = "vsdhfnmsdbvfuf121535435aewr"
var result = string.filter { it.isDigit() }

I got this from here: https://stackoverflow.com/a/57316352

Upvotes: 117

Willi Mentzel
Willi Mentzel

Reputation: 29844

replace will not mutate the String str, that's why it is ok for str to be immutable (val) which it should be.

val str = "vsdhfnmsdbvfuf121535435aewr"
val num = str.replace(Regex("[^0-9]"), "")
println(num)

Output:

4545121535435


Since the title of your questions reads "numbers": In case you have multiple numbers scattered across the String you can use Regex.findAll. This is also a more fail safe solution because if you just remove what is around numbers then you might end up interpreting "a1b2c3" as "123" instead of as "[1 ,2 ,3]".

val str = "vsdhfn4545msdbvfuf121535435aewr"
val numbers = Regex("[0-9]+").findAll(str)
        .map(MatchResult::value)
        .toList()

println(numbers)

Output:

[4545, 121535435]

Upvotes: 4

Enzo Lizama
Enzo Lizama

Reputation: 1315

The replace method returns a new String, not modify the base. You can try this here, and will work for you.

var s1 = "vsdhfnmsdbvfuf121535435aewr"  
var s2 = s1.replace("[^0-9]".toRegex(), "")
print(s2)

Upvotes: 3

salmanwahed
salmanwahed

Reputation: 9647

Your code is working fine. Here string is immutable. So it's value can't be changed. But you can assign another variable to the replaced string.

fun main(args: Array<String>) {
    var string = "vsdhfnmsdbvfuf121535435aewr"
    var res = string.replace("[^0-9]".toRegex(), "")
    println(res)
}

Upvotes: 7

Related Questions