Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir punctuation replacement regex

Tags:

regex

elixir

I'm trying to remove all punctuation from a string using

String.replace(sentence, ~r[\p{P}\p{S}], "")

However it's not removing all punctuation! As an illustrative example:

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

What should I be using?

like image 248
Joshua Hannah Avatar asked Sep 13 '14 01:09

Joshua Hannah


1 Answers

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.

like image 128
lordB8r Avatar answered Oct 06 '22 22:10

lordB8r