简体   繁体   中英

Replace special character with its index

I need to replace all special characters within a string with their index. For example,

"I-need_to@change$all%special^characters^"

should become:

"I1need6to9change16all20special28characters39"

The index of all special character differs. I have checked many links replacing all with single character , occurances of a character . I found very similar link but it I do not want to adopt these replace its index number as I need to replace all of the special characters.

I have also tried to do something like this:

str.gsub!(/[^0-9A-Za-z]/, '')

Here str is my example string. As this replaces all the characters but with space, and I want the index instead of space. Either all of the special character or these seven

\/*[]:?

I need to replace this seven mainly but it would be OK if we replace all of them.

I need a simpler way.

Thanks in advance.

You can use the global variable $` and the block form of gsub :

irb> str = "I-need_to@change$all%special^characters^"
=> "I-need_to@change$all%special^characters^"
irb> str.gsub(/[^0-9A-Za-z]/) { $`.length }
=> "I1need6to9change16all20special28characters39"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM