port5432
port5432

Reputation: 6403

Ruby: Remove number from embedded string

In a Rails app I am reading a file with key/values. An index number is embedded in the key name, and I'd like to remove it, along with one of the spacing underscores.

So in the sample data below, I'd like to convert:

Sample Data

PRIMER_LEFT_1_END_STABILITY=7.2000

PRIMER_RIGHT_1_END_STABILITY=7.9000

PRIMER_PAIR_1_COMPL_ANY_TH=0.00

EDIT

Thanks to @tihom for the first answer. It's partially working, but I did not specify that the embedded integer can be of any value. When over 1 digit in length the regex fails:

1.9.3-p327 :003 > "PRIMER_LEFT_221_END_STABILITY".sub(/_\d/,"")
 => "PRIMER_LEFT21_END_STABILITY"
1.9.3-p327 :004 > "PRIMER_LEFT_21_END_STABILITY".sub(/_\d/,"")
 => "PRIMER_LEFT1_END_STABILITY"

Upvotes: 0

Views: 80

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118299

You can use String#tr and String#squeezeas below :

ar=['PRIMER_LEFT_1_END_STABILITY','PRIMER_RIGHT_1_END_STABILITY','PRIMER_PAIR_1_COMPL_ANY_TH']
p ar.map{|s| s.tr('0-9','').squeeze("_")}
# => ["PRIMER_LEFT_END_STABILITY", "PRIMER_RIGHT_-END_STABILITY", "PRIMER_PAIR_COMPL_ANY_TH"]


ar=["PRIMER_LEFT_221_END_STABILITY","PRIMER_LEFT_21_END_STABILITY"]
p ar.map{|s| s.tr('0-9','').squeeze("_")}
# => ["PRIMER_LEFT_END_STABILITY", "PRIMER_LEFT_END_STABILITY"]

Upvotes: 1

tihom
tihom

Reputation: 8003

To remove the first occurrence use sub else to remove all occurrences use gsub

"PRIMER_LEFT_1_END_STABILITY".sub(/_(\d)+/,"") # => "PRIMER_LEFT_END_STABILITY" 

"+" matches one or more of the preceding character. So in this case it matches one or more of any digit followed by a "_"

Upvotes: 1

Related Questions