I need help with creating a regex that removes all special characters, including commas, but not periods. What I have tried to do is escape all the characters, symbols and punctuation I do not want. It is not working as intended.
replace("[-\\[\\]^/,'*:.!><~@#\$%+=?|\"\\\\()]+".toRegex(), "")
I removed the period and tested that too. It did not work.
replace("[-\\[\\]^/,'*:!><~@#\$%+=?|\"\\\\()]+".toRegex(), "")
For example, lets take the String "if {cat.is} in a hat, then I eat green eggs and ham!".
I want the result
if {cat.is} in a hat then I eat green eggs and ham
(comma and exclamation symbol removed)
Note: I want to keep brackets, although braces are OK to omit.
Anyone have a solution for this?
You can use
"""[\p{P}\p{S}&&[^.]]+""".toRegex()
The [\\p{P}\\p{S}&&[^.]]+
pattern matches one or more ( +
) punctuation proper ( \\p{P}
) or symbol ( \\p{S}
) chars other than dots ( &&[^.]
, using character class subtraction).
See a Kotlin demo :
println("a-b)h.".replace("""[\p{P}\p{S}&&[^.]]+""".toRegex(), ""))
// => abh.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.