Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorter way to remove non-characters than gsub(/\d|\W/, "")

my_string = 'Here's the #: 49848! - but will dashes, commas & stars (*) show?'

puts src.gsub(/\d|\W/, "")

i.e. can I remove the or ("|").

Here's how I got here, can I get shorter?

src =  "Here's the #: 49848! - but will dashes, commas & stars (*) show?"
puts "A) - " + src
puts "B) - " + src.gsub(/\d\s?/, "")
puts "C) - " + src.gsub(/\W\s?/, "")
puts "D) - " + src.gsub(/\d|\W\s?/, "")
puts "E) - " + src.gsub(/\d|\W/, "")
puts "F) - " + src

A) - Here's the #: 49848! - but will dashes, commas & stars (*) show?
B) - Here's the #: ! - but will dashes, commas & stars (*) show?
C) - Heresthe49848butwilldashescommasstarsshow
D) - Heresthebutwilldashescommasstarsshow
E) - Heresthebutwilldashescommasstarsshow
F) - Here's the #: 49848! - but will dashes, commas & stars (*) show?

n.d. D) and E) are what I want for output. Just characters.

like image 356
Michael Durrant Avatar asked Feb 02 '12 20:02

Michael Durrant


People also ask

How do I get rid of non numeric characters in R?

We will remove non-alphanumeric characters by using str_replace_all() method. [^[:alnum:]] is the parameter that removes the non-alphanumeric characters.

How do I remove GSUB from R?

To remove a character in an R data frame column, we can use gsub function which will replace the character with blank. For example, if we have a data frame called df that contains a character column say x which has a character ID in each value then it can be removed by using the command gsub("ID","",as.

What is GSUB in regex?

The “sub” in “gsub” stands for “substitute”, and the “g” stands for “global”. Here is an example string: str = "white chocolate" Let's say that we want to replace the word “white” with the word “dark”. Here's how: str.gsub("white", "dark")

Does GSUB use regex?

Regular expressions (shortened to regex) are used to operate on patterns found in strings. They can find, replace, or remove certain parts of strings depending on what you tell them to do.


1 Answers

my_string = "Here's the #: 49848! - but will dashes, commas & stars (*) show?"
p my_string.delete('^a-zA-Z')
#=>"Heresthebutwilldashescommasstarsshow"
like image 80
steenslag Avatar answered Oct 01 '22 06:10

steenslag