繁体   English   中英

如何替换字符串中的指定空格?

[英]How can I replace specified whitespaces in string?

我有一个字符串:

2+3-{Some value}

如何防止用户在运算符和操作数之间添加空格,但允许在大括号之间添加空格? 也许正则表达式?

更新

我正在研究实时验证公式。 包括空格删除在内的所有验证都使用TextWatcher完成。 我的简化代码如下所示:

private val formulaWatcher: TextWatcher = object : TextWatcher {
        override fun afterTextChanged(s: Editable?) = Unit

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit

        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            //Delay used here to avoid IndexOfBoundExceptions which arise because of a setSelection() method, it works with a little delay
            Handler().postDelayed({
                removeSpaces(s)
            }, 100)
        }
    }

删除空格函数:

private fun removeSpaces(s: CharSequence) {
        if (s.last().isWhitespace()) {
            val textWithoutSpaces = s.replace(Regex("\\s"), "")
            getText().clear()
            append(textWithoutSpaces)
            setSelection(textWithoutSpaces.length)
        }
    }

日期

根据您提供的代码片段,我修改了答案。 首先,使用trim() 函数从输入字符串的开头和结尾删除空格。 修剪字符串后,使用以下正则表达式来达到所需的模式。

private fun removeSpaces(s: CharSequence) {
    // e.g. s is " 2 + 3 - { some value } " 
    s = s.trim()
    // now s is "2 + 3 - { some value }"

    // define a regex matching a pattern of characters including some spaces before and after an operator (+,-,*,/)
    val re = Regex("""\s*([\+\-\*\/])\s*""")

    // $1 denotes the group in the regex containing only an operator
    val textWithoutSpaces = re.replace(s, "$1")
    // textWithoutSpaces is "2+3-{ some value }"

    getText().clear()
    append(textWithoutSpaces)
    setSelection(textWithoutSpaces.length)
}

正则表达式的工作方式是查找每个运算符,即+-*/以及它前后的空格。 通过使用括号对操作符本身进行分组,包括额外空格在内的所有模式都被仅替换为没有任何额外空格的操作符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM