【发布时间】:2019-04-16 01:23:32
【问题描述】:
我有一个字符串:
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)
}
}
【问题讨论】:
-
请阅读“如何创建minimal reproducible example”。然后使用edit 链接改进您的问题(不要通过 cmets 添加更多信息)。否则我们无法回答您的问题并为您提供帮助。向我们展示一个完整的示例和您拥有的代码,并告诉我们它与您的期望有什么不同。
-
也许是正则表达式? - 使用
String::replaceAll的好主意 -
@ScaryWombat replaceAll 将替换字符串中的所有空格。我需要在大括号之间保存空格
标签: java android string replace kotlin