正则表达式一个字符串
regular expression a string
我需要一个正则表达式来转换以下对象:
"{:email=>[\"has already been taken\"], :name=>[\"has already been taken\"]}"
到
Email has already been taken, Name has already been taken
▶ str = "{:email=>[\"has already been taken\"], :name=>[\"has already been taken\"]}"
▶ eval(str).map { |k, v| [k.capitalize, v].join(' ') }.join(', ')
#⇒ "Email has already been taken, Name has already been taken"
与scan
:
▶ str.scan(/:(\w+)=>\["(.*?)"\]/).map do |k, v|
▷ [k.capitalize, v].join(' ')
▷ end.join(', ')
#⇒ "Email has already been taken, Name has already been taken"
另一种方法:
def convert(str)
arr = [' '].concat str.chars
str.gsub(/./) do |c|
case arr.shift
when ':' then c.upcase
when '=' then ' '
else c =~ /[,\sa-zA-Z]/ ? c : ''
end
end
end
str = '{:email=>[\"has already been taken\"], :name=>[\"has already been taken\"]}'
convert str
#=> "Email has already been taken, Name has already been taken"
我需要一个正则表达式来转换以下对象:
"{:email=>[\"has already been taken\"], :name=>[\"has already been taken\"]}"
到
Email has already been taken, Name has already been taken
▶ str = "{:email=>[\"has already been taken\"], :name=>[\"has already been taken\"]}"
▶ eval(str).map { |k, v| [k.capitalize, v].join(' ') }.join(', ')
#⇒ "Email has already been taken, Name has already been taken"
与scan
:
▶ str.scan(/:(\w+)=>\["(.*?)"\]/).map do |k, v|
▷ [k.capitalize, v].join(' ')
▷ end.join(', ')
#⇒ "Email has already been taken, Name has already been taken"
另一种方法:
def convert(str)
arr = [' '].concat str.chars
str.gsub(/./) do |c|
case arr.shift
when ':' then c.upcase
when '=' then ' '
else c =~ /[,\sa-zA-Z]/ ? c : ''
end
end
end
str = '{:email=>[\"has already been taken\"], :name=>[\"has already been taken\"]}'
convert str
#=> "Email has already been taken, Name has already been taken"