Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 从字符串中删除除字符以外的所有内容?_Ruby - Fatal编程技术网

Ruby 从字符串中删除除字符以外的所有内容?

Ruby 从字符串中删除除字符以外的所有内容?,ruby,Ruby,我现在从ruby开始,在我的课程作业中,它被要求操作字符串,这就提出了一个问题 给定一个字符串链接: I'm the janitor, that's what I am! 任务是从字符串中删除除字符以外的所有内容,以便生成结果 IamthejanitorthatswhatIam 实现这一目标的一个方法是 "I'm the janitor, that's what I am!".gsub(" ", "").gsub(",","").gsub("'","").gsub("!","") 这是可行

我现在从ruby开始,在我的课程作业中,它被要求操作字符串,这就提出了一个问题

给定一个字符串链接:

I'm the janitor, that's what I am!
任务是从字符串中删除除字符以外的所有内容,以便生成结果

IamthejanitorthatswhatIam
实现这一目标的一个方法是

"I'm the janitor, that's what I am!".gsub(" ", "").gsub(",","").gsub("'","").gsub("!","")
这是可行的,但看起来相当笨拙。处理此任务的另一种方法可能是正则表达式。有没有更“红宝石”的方法来实现这一点


提前感谢

.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" 
正如@nhahdh所指出的,这包括数字和下划线

可以不执行此任务而完成此任务的正则表达式是
/[^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" 

gsub(“[^a-zA-Z]”,“)
应该删除所有非英语字母。我想你的意思是
/[^a-zA-Z]/
。@AdamEberlin:我不确定ruby语法,因为我不使用它。我只知道正则表达式。你认为什么是“角色”?
µ
é
是字符吗?
?谢谢你的建议。在重新检查了gsub的文档之后,我意识到可以在其中使用正则表达式,而不仅仅是单个字符。我使用str.gsub(/[^a-zA-Z]/,“”)来处理我的字符串,因为它足以完成家庭作业中要求的任务。我不知道OP想要什么,但
\W
除了英文字母上下、0-9位数字和下划线外,其他都是。