33

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(), "")
Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
Ho Binh
  • 351
  • 1
  • 3
  • 8

10 Answers10

101

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

jj.
  • 2,210
  • 3
  • 21
  • 22
7

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)
}
salmanwahed
  • 9,450
  • 7
  • 32
  • 55
4

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]

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
4

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())
Prasad
  • 3,462
  • 1
  • 23
  • 28
  • You mean to say that stripping "Rs. 1,00,000.00" would end up with 10000000, not 100000. But thats ok, as it would be a bankers value, it's in cents, so just divide by 100, and you get 100000.00. – Brill Pappin Sep 14 '22 at 20:20
  • @BrillPappin If this is the case, how can we handle Rs. 123 and Rs. 123.00? I have explained the limitations of the regex method and the filtering only digits method. – Prasad Sep 19 '22 at 09:13
  • Rs. 123 is invalid, or rather is seen as 1.23, but rs 123.00 would be seen as 12300. This is expected. If you are converting input, you want it to work this way. As the user types they are adding cents. The other potential use is parsing a bunch of corrupt data. In that case you'd want to fix the data first. – Brill Pappin Sep 21 '22 at 10:32
3

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)
Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
Enzo Lizama
  • 1,214
  • 1
  • 14
  • 23
2

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

1

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(), "")
Thành Hà Văn
  • 481
  • 2
  • 9
0

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){
      }
Muhammad Mubeen
  • 153
  • 1
  • 8
0

Try this we will get result

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

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

string.replaceAll(int, "")
Semyon Tikhonenko
  • 3,872
  • 6
  • 36
  • 61