Manjunath P Manjunath P - 4 months ago 12
Ruby Question

Replace words containing numbers in Ruby

In my string, I want to skip words containing numbers and skip symbols or special characters

!
,
-
,
/
,
%
,
$
,
#
,
@
,
~
,
*
.

str = "Catheter 16G - 50"


Expected result:

"Catheter"


Words could be like:

16, GG, 16G, G16, 1G6, 16-G, 16/G, G-16, 16/G, 1G6G, G1G6, G16G, 1GG6, etc.


I could only write this:

str.gsub(/[0-9]+/,"").squish
# => "Catheter - G"


Kindly help me achieve this.


Edited





.strip has been replaced by .squish in the above question.

Answer

You can try this:

 str.gsub(/([\s]*[^\s]*[^a-zA-Z\s]+[^\s]*[\s]*)/,"").strip

It would replace words, containing numbers and/or special characters.

Comments