我有一个字符串:
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)
}
}
最佳答案
更新
根据您提供的代码 fragment ,我修改了答案。 首先,使用 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)
}
正则表达式的工作方式是找到每个运算符,即 +
、-
、*
和 /
以及它前后的空格。通过使用括号对运算符本身进行分组,包括额外空格的所有模式都将仅替换为没有任何额外空格的运算符。
关于java - 如何替换字符串中的指定空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53277138/