Home > Blockchain >  How to add spacing between currency and amount which is inside a string?
How to add spacing between currency and amount which is inside a string?

Time:11-24

My string in Ruby contains currency and amount.

I have purchased and item at USD500.80 from online store store 123X87

I am expecting following result

I have purchased and item at USD 500.80 from online store store 123X87

I tried with Regex but not succeed.

str = "I have purchased and item at USD500.80 from online store store 123X87"

str.gsub(/\d /, ' \0 ')

# wrong result

"I have purchased and item at USD 500 . 80  from online store store  123 X 87 "

I am not sure what currency that string contains. I only know currency and amount do not have space.

str = "I have purchased and item at EUR500.80 from online store store 123X88"

str = "I have purchased and item at GBP500.80 from online store store 123X88"

CodePudding user response:

I'd change the regex to scan for all known currency codes explicitly. Any over-generalized regex (such as \w \d , for example) is bound to break other parts of the string, like order numbers.

str = "I have purchased and item at USD500.80 from online store store 123X87"
str.gsub(/(USD|EUR)(\d )/, '\1 \2')
# => "I have purchased and item at USD 500.80 from online store store 123X87"
  • Related