Regex to remove all special characters except periods

Viewed 1179

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?

1 Answers

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.
Related