Home > OS >  How to get integer with regular expression in kotlin?
How to get integer with regular expression in kotlin?

Time:04-27

ViewModel

fun changeQty(textField: TextFieldValue) {
    val temp1 = textField.text
    Timber.d("textField: $temp1")
    val temp2 = temp1.replace("[^\\d]".toRegex(), "")
    Timber.d("temp2: $temp2")
    _qty.value = textField.copy(temp2)
}

TextField

                OutlinedTextField(
                    modifier = Modifier
                        .focusRequester(focusRequester = focusRequester)
                        .onFocusChanged {
                            if (it.isFocused) {
                                keyboardController?.show()
                            }
                        },
                    value = qty.copy(
                        text = qty.text.trim()
                    ),
                    onValueChange = changeQty,
                    label = { Text(text = qtyHint) },
                    singleLine = true,
                    keyboardOptions = KeyboardOptions(
                        keyboardType = KeyboardType.Number,
                        imeAction = ImeAction.Done
                    ),
                    keyboardActions = KeyboardActions(
                        onDone = {
                            save()
                            onDismiss()
                        }
                    )
                )

Set KeyboardType.Number, it display 1,2,3,4,5,6,7,8,9 and , . - space. I just want to get integer like -10 or 10 or 0. But I type the , or . or -(not the front sign), it show as it is.

ex) typing = -10---------

hope = -10

display = -10---------

I put regular expression in

val temp2 = temp1.replace("[^\\d]".toRegex(), "")

But, it doesn't seem to work. How I can get only integer(also negative integer)?

CodePudding user response:

Use this regex (?<=(\d|-))(\D ) to replace all non digit characters, except first -.

fun getIntegersFromString(input: String): String {
    val pattern = Regex("(?<=(\\d|-))(\\D )")
    val formatted = pattern.replace(input, "")
    return formatted
 }

Check it here

  • Related