【问题标题】:Regex to remove all special characters except periods正则表达式删除除句点以外的所有特殊字符
【发布时间】:2020-09-14 11:02:23
【问题描述】:

我需要帮助创建一个删除所有特殊字符(包括逗号,但不包括句点)的正则表达式。我试图做的是转义所有我不想要的字符、符号和标点符号。它没有按预期工作。

replace("[-\\[\\]^/,'*:.!><~@#\$%+=?|\"\\\\()]+".toRegex(), "")

我删除了句号并对其进行了测试。它没有用。

replace("[-\\[\\]^/,'*:!><~@#\$%+=?|\"\\\\()]+".toRegex(), "")

例如,让我们以字符串“如果 {cat.is} 在帽子里,那么我吃绿色鸡蛋和火腿!”。

我想要结果

if {cat.is} in a hat then I eat green eggs and ham(去掉逗号和感叹号)

注意:我想保留括号,尽管可以省略括号。

有人有解决办法吗?

【问题讨论】:

  • 是的。我正在使用科特林。让我将其添加到我的问题中。

标签: android regex kotlin


【解决方案1】:

你可以使用

"""[\p{P}\p{S}&&[^.]]+""".toRegex()

[\p{P}\p{S}&amp;&amp;[^.]]+ 模式匹配一​​个或多个 (+) 标点符号 (\p{P}) 或符号 (\p{S}) 字符而非点(&amp;&amp;[^.],使用字符类减法)。

查看Kotlin demo

println("a-b)h.".replace("""[\p{P}\p{S}&&[^.]]+""".toRegex(), ""))
// => abh.

【讨论】:

  • 感谢您的回答。我用“if {cat.is} in a hat, then I eat green eggs and ham!”.replace("""[\p{P}\p{S}&&[^.]]+"" ".toRegex(), "")。我期待逗号和!将被删除,但事实并非如此。
  • @portfoliobuilder 见this Kotlin demoif {cat.is} in a hat, then I eat green eggs and ham! 变成 if cat.is in a hat then I eat green eggs and ham
猜你喜欢
  • 2014-01-10
  • 2021-10-11
  • 1970-01-01
  • 2016-05-26
  • 1970-01-01
  • 1970-01-01
  • 2011-03-19
  • 1970-01-01
相关资源
最近更新 更多