Elixir punctuation replacement regex

Possibly need /.../ as pattern delimiters:

String.replace("foo!&^%$?", ~r/[\p{P}\p{S}]/, "")

The result could be explained, because else [ ] would be used as delimiters in your sample, which corresponds to \p{P}\p{S} as a sequence and results in foo!? (see regex101 example)

Would additionally add a + quantifier: ~r/[\p{P}\p{S}]+/


If you're only working with strings in English, it's easiest and clearest to just use POSIX character classes:

String.replace("foo!&^%$?", ~r/[[:punct:]]/, "")


I'm late to the game, but you have to adjust the regex and customize it, especially if you're trying to preserve certain items, like a hyphen (which is considered punctuation in some language aspects).

My replace is a bit more verbose, but lets me control what I want to replace:

String.replace(str, ~r/[!#$%&()*+,.:;<=>?@\^_`{|}~-]/, "")

This let me keep the hyphen in a word, like co-operate, while removing :or other characters.

Tags:

Regex

Elixir