我目前正在开始使用ruby,并且在我的课程作业中,它被要求操纵字符串,这提出了一个问题。
给出一个字符串链接:
I'm the janitor, that's what I am!
任务是删除字符串中除字符之外的所有内容,以便结果为
IamthejanitorthatswhatIam
实现这一目标的一种方法是
"I'm the janitor, that's what I am!".gsub(" ", "").gsub(",","").gsub("'","").gsub("!","")
这有效,但看起来很笨拙。处理此任务的另一种方法可能是正则表达式。是否有更多的“红宝石”来实现这一目标?
提前致谢
答案 0 :(得分:4)
使用正则表达式代替.gsub
中的字符串,例如/\W/
,与非字符字符匹配:
ruby-1.9.3-p194 :001 > x = "I'm the janitor, that's what I am!"
=> "I'm the janitor, that's what I am!"
ruby-1.9.3-p194 :002 > x.gsub(/\W/, '')
=> "ImthejanitorthatswhatIam"
正如@nhahtdh指出的,这包括数字和下划线。
可以完成此任务的正则表达式是/[^a-zA-Z]/
:
ruby-1.9.3-p194 :001 > x = "I'm the janitor, that's what I am!"
=> "I'm the janitor, that's what I am!"
ruby-1.9.3-p194 :003 > x.gsub(/[^a-zA-Z]/, "")
=> "ImthejanitorthatswhatIam"