【问题标题】:How can I replace specified whitespaces in string?如何替换字符串中的指定空格?
【发布时间】: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


【解决方案1】:

UDATE

根据您提供的代码 sn-p,我修改了答案。 首先,使用 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)
}

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

【讨论】:

  • 谢谢,但这不起作用。因为它只从开头和结尾删除空格。如果我们像这样粘贴字符串:2+ {oper 1},我们将得到:2+ {oper 1}
  • 从您的更新和 cmets 来看,我认为您的意思是 2 + 3 - { any string } 必须转换为 2+3-{ any string }。我说的对吗?
  • @Skullper 我在解决方案中添加了一个正则表达式并对其进行了测试。它工作正常。
  • @Abdolah 哇,谢谢,它真的很有帮助。我已经尝试使用前瞻的正则表达式,但您的解决方案更复杂)
猜你喜欢
  • 2013-11-21
  • 2013-05-09
  • 2019-05-16
  • 2018-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-03
  • 2021-06-21
相关资源
最近更新 更多