owaisqayum
Usage of String.replace?
I have a sample string
sentence = "Hello, world ... 123 *** ^%&*())^% %%:>"
From this string, I want to only keep the integers, characters, and spaces. For that, I have used String. replace like this
a = String.replace(sentence, ~r"[:_!@#$%^&*:|,./]", " ")
Here it’s replacing the second argument with the third one that is an empty space.
Is there any way that we can use String.replace and focus on what to keep rather than what to throw away.
Thanks
Most Liked
axelson
Not super important but for clarity I’d like to point out that the caret character ^ is not the pin operator in this case, it is acting as a regex negation operator.
Eiji
@owaisqayum: You can use ^ (negation character) like:
sentence = "Hello, world ... 123 *** ^%&*())^% %%:>"
String.replace(sentence, ~r/[^0-9a-zA-Z ]/, " ")
Here is my another post with many helpful examples:
On pages for testing regular expressions you may find some references. For example here:
at the bottom of page you can search by not and you would have few interesting suggestions.
A CHARACTER NOT IN THE RANGE A-Z
[^a-z]Matches any characters except those in the range a-z.
/[^a-z]+/g
Anythingbuta-z.
al2o3cr
In this case, the negation option for a character class will do what you want - ~r([^A-Z]) will match anything that isn’t A-Z (indicated by the leading ^.
Popular in Discussions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









