开发者

Ruby One-liner Regular Expression to replace each character \d with "*"?

开发者 https://www.devze.com 2023-02-02 18:49 出处:网络
How do you replace each character up to a certain point wit开发者_JAVA百科h another character as long as a condition is met?

How do you replace each character up to a certain point wit开发者_JAVA百科h another character as long as a condition is met?

string = "401200******7777"

string.gsub!(/^\d+/) { |m| "*" * m.length }

puts string
# ************7777

Is there an easier/better way to do this?


Can't try it right now, but this should do the trick:

string.gsub!(/(\d)(?=.*\*)/, '*')


Hmmm... the only way I invented now is using flag variable + two regexes:

string = "401200******7777"
flag = true
string.gsub!(/./) { |i| (flag &&= i[/\d/]) ? "*" : i}

But it's not oneliner...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号