Remove Punctuation in Clojure

Practical Clojure examples for removing punctuation from strings, including regex approaches, Unicode behavior, and output checks.

Before you start

This task runs locally in a Clojure REPL or Clojure source file. No external image, audio, or camera service is involved. Have a working Clojure environment available so you can evaluate the forms directly.

The main tool is the regular expression engine built into Clojure. Punctuation can be matched with a character class such as \p{Punct}, which covers common ASCII punctuation, or with \p{P}, which is the broader Unicode punctuation category.

Step-by-step instructions

Start with a small function that removes matched punctuation using clojure.string/replace and a regular expression.

A basic ASCII-oriented version looks like this: (require '[clojure.string :as str]) followed by (str/replace "Hello, world!" #"[\p{Punct}]" ""). The result is "Hello world".

For broader Unicode handling, use the punctuation category pattern: #"\p{P}+". This class also includes marks such as dashes and quotation marks from the Unicode punctuation category.

For a named helper that is easier to reuse, define a function such as (defn remove-punctuation [s] (str/replace s #"\p{P}+" "")). Then call it with the string you need to clean.

If you only want to remove punctuation from the beginning and end of a string, use a trimmed pattern instead: #"^[\p{P}\s]+|[\p{P}\s]+$". This preserves internal punctuation while cleaning the edges.

When processing text from a file, read the content with slurp, apply the function, and write the result with spit. This keeps the change reversible if you preserve the original file first.

Check the output

Compare the returned string with the expected clean text. For "Hello, world!" the output should have no comma or exclamation mark.

Be aware that punctuation removal may collapse spacing or join separated words. The original word boundaries are not restored automatically, so review cases where punctuation acted as a separator.

Common problems and next steps

A frequent issue is using a character class that removes too little or too much. \p{Punct} is narrower than \p{P}, so decide whether you need ASCII-only behavior or broader Unicode punctuation coverage.

Another issue is accidentally removing apostrophes inside words such as "don't." If apostrophes should be kept, use an explicit character class that omits them rather than relying on a broad punctuation category.

Regex escaping in Clojure is different from some other languages. A double backslash is needed inside regular expression syntax, while literal backslashes may require additional escaping in strings. Test a short sample first when a pattern does not behave as expected.