[ACCEPTED]-Strip/replace spaces within a string-regex

Accepted answer
Score: 34

If you want to do the replacement in place, you 8 need to use:

str.gsub!(/\s/,'')

Alternatively, gsub returns 7 the string with the replacements

str2 = str.gsub(/\s/,'')

EDIT: Based 6 on your answer, it looks like you have some 5 unprintable characters embedded in the string, not 4 spaces. Using /\D/ as the search string may 3 be what you want. The following will match 2 any non-digit character and replace it with 1 the empty string.

str.gsub!(/\D/,'')
Score: 14
>> "5 900 00".gsub(' ','')
=> "590000"

Is it really a string?

.gsub returns the 2 value, if you want to change the variable 1 try .gsub!(" ", "")

Score: 5

Just for kicks: do you even need a regular 9 expression here? String#tr should do the trick just 8 fine:

telemachus ~ $ irb
>> "500 500 12".tr(' ', '')
=> "50050012"
>> "500 500 12".tr!(' ', '')
=> "50050012"

As with gsub and gsub!, the ! method makes the 7 change in place as opposed to returning 6 the changed result. I don't know which you 5 want here.

In a case like this, tr seems more 4 straightforward to me. I'm not looking for 3 optimization, but it is good to remember 2 that there are lots of string methods other than 1 regular expressions.

Score: 2

I suggest doing str.gsub!(/\s+/, '') for efficiency reasons.

0

Score: 2

Try this hope this will helpful :

2.2.1 :001> str= "  Jai   Kumar rajput ";
  # "  Jai   Kumar rajput "
2.2.1 :001> str.squish.downcase.tr(" ","");
  # "JaiKumarRajput" 

0

Score: 1

"5 900 000".gsub(/\s/,'') works fine

From what I see you wrote gsub 1 dot (foo,bar) where it must be string.gsub(foo,bar)

Score: 0
print "5 900 000".gsub(/\s/, '')

Works for me.

Are you affecting the result 1 to the variable ?

Score: 0

do you mean

str.gsub!.(/\s/,'')

with the exclamation mark?

0

Score: 0

The funny thing is that when I print the 5 string i get

697\302\240000

but what gets 4 to the database is: 697 000. I know that 3 patterns i have given should work as well 2 as your suggestions, but this seems to be 1 a little bit 'dodgy' case :-)

More Related questions