简体   繁体   中英

Is there a way to replace a range of characters in a string using gsub?

I would like to replace every character except the last 4 with a "#"...like you would see on a credit card statement. I have accomplished this using the Array#each method to iterate through indexes [0..-4] and then another for [-4..-1] and shoveling results from both into a new string. I'm thinking that maybe this could be better done with regex? But I am new to regex, and google hasn't turned up anything I can use in regards to replacing an entire range without losing the length of the string. I have tried

str.gsub(str[0..-5],'#')

(and a few other things) but it replaces the entire range with a single character. How can I accomplish my goal using regex?

Yep, this is possible with regex.

> "12345678".gsub(/.(?=.{4})/, "#")
=> "####5678"
> "12345678901234".gsub(/.(?=.{4})/, "#")
=> "##########1234"

Explanation:

.(?=.{4}) matches a character only if it's followed by atleast four characters. So it matches all the characters except the last four chars because from the last, fourth character is followed by 3 characters not 4. So it fails to match the 4th char from the last. Likewise for 3rd, 2nd, 1st chars ( from the last ).

OR

> "12345678901234".gsub(/(?!.{1,4}$)./, "#")
=> "##########1234"

DEMO

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