开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜