Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(), "")
like image 823
Ho Binh Avatar asked Nov 12 '19 04:11

Ho Binh


People also ask

How do I get only numbers from string in Kotlin?

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

How extract only numbers from string in shell script?

Replaces all non numbers with spaces: sed -e 's/[^0-9]/ /g' Remove leading white space: -e 's/^ *//g' Remove trailing white space: -e 's/ *$//g' Squeeze spaces in sequence to 1 space: tr -s ' '

How do you split a string in Kotlin?

Using String's split() function The standard solution to split a string in Kotlin is with the native split() function, which takes one or more delimiters as an argument and splits the string around occurrences of the specified delimiters. The split() function returns a list of strings.

How do you check if a string is a number Kotlin?

To check if string contains numbers only, in the try block, we use Double 's parseDouble() method to convert the string to a Double . If it throws an error (i.e. NumberFormatException error), it means string isn't a number and numeric is set to false . Else, it's a number.


6 Answers

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

like image 94
jj. Avatar answered Oct 20 '22 15:10

jj.


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)
}
like image 28
salmanwahed Avatar answered Oct 20 '22 15:10

salmanwahed


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())
like image 22
Prasad Avatar answered Oct 20 '22 15:10

Prasad


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)
like image 34
Enzo Lizama Avatar answered Oct 20 '22 15:10

Enzo Lizama


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]

like image 40
Willi Mentzel Avatar answered Oct 20 '22 15:10

Willi Mentzel


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(), "")
like image 30
Thành Hà Văn Avatar answered Oct 20 '22 15:10

Thành Hà Văn