I want to remove all characters in a string except:
-
or _
or .
A
thru Z
a
thru z
0
to 9
On linux command line, using sed
I would do this:
$ echo "testing-#$% yes.no" | sed 's/[^-_.a-zA-Z0-9 ]//g'
Output:
testing- yes.no
How can I achieve the same effect in Red language with PARSE? I looked at:
However, I could not codify it. I tried:
>> parse "mystring%^&" [#a - #z #A - #Z #0 - #9]
== false
>> parse "mystring%^&" [#a-#z#A-#Z#0-#9]
== false
In Ruby, we can permanently delete characters from a string by using the string. delete method. It returns a new string with the specified characters removed.
Using str_replace() Method: The str_replace() method is used to remove all the special characters from the given string str by replacing these characters with the white space (” “).
First note the difference between ISSUE! and CHAR!
#a #b #c ; issues
#"a" #"b" #"c" ; chars
You can then establish a character set (BITSET! type) either for the characters you want to keep or those you wish to discard. We'll do the former here:
good-chars: charset [#"a" - #"z" #"A" - #"Z" #"0" - #"9"]
Now that we have that, we can approach this in some different ways:
A fairly basic parse loop—skips any good-chars
and removes anything else.
parse "mystring%^&" [any [some good-chars | remove skip]]
Hopefully self-explanatory:
remove-each char "mystring%^&" [not find good-chars char]
First, characters must be in quotes, #a
is issue!
, char!
is #"a"
. You've got the specification right, but you must pass it to charset
function, to make a bitset!
form it.
Then you can parse
your string, keep
ing valid characters and skip
ing invalid:
>> chars: charset [#"a" - #"z" #"A" - #"Z" #"0" - #"9"]
== make bitset! #{000000000000FFC07FFFFFE07FFFFFE0}
>> rejoin parse "mystring%^&asdf" [collect some [keep chars | skip]]
== "mystringasdf"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With