ruby - 使用 select 而不是 gsub 来避免在 Ruby 中进行多个正则表达式评估

标签 ruby regex gsub

这是一个输出,需要多个正则表达式评估,但可以完成我想做的事情(删除除文本以外的所有内容)。

words = IO.read("file.txt").
gsub(/\s/, ""). # delete white spaces
gsub(".",""). # delete periods
gsub(",",""). # delete commas
gsub("?","") # delete Q marks
puts words
# output
#      WheninthecourseofhumaneventsitbecomesnecessaryIwanttobelieveyoureallyIdobutwhoamItoblameWhenthefactsarecountedthenumberswillbereportedLotsoflaughsCharlieIthinkIheardthatonetentimesbefore

查看这篇文章 - Ruby gsub : is there a better way - 我想我会尝试进行匹配以在没有多个正则表达式评估的情况下完成相同的结果。但我没有得到相同的输出。

words = IO.read("file.txt").
match(/(\w*)+/)
puts words
# output - this only gets the first word
# When

这只会得到第一句话:

words = IO.read("file.txt").
match(/(...*)+/)
puts words

# output - this only gets the first sentence
# When in the course of human events it becomes necessary.

关于在匹配而不是 gsub 上获得相同输出(包括去除空格和非单词字符)的任何建议?

最佳答案

你可以在一个 gsub 操作中做你想做的事:

s = 'When in the course of human events it becomes necessary.'
s.gsub /[\s.,?]/, ''
# => "Wheninthecourseofhumaneventsitbecomesnecessary"

关于ruby - 使用 select 而不是 gsub 来避免在 Ruby 中进行多个正则表达式评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10293012/

相关文章:

java - RJB Hello World 示例

javascript - 正则表达式: Match text node only in a tag

ruby : "undefined method"错误;如何更有效地使用 gsub?

ruby-on-rails - 我该如何修复这个创建功能?

ruby - 如何在 ruby​​ 中解析符号

c# - 正则表达式匹配组

替换类 'expression' 的 R 对象中的字符

r - 如何在R中用相同的字符串替换多个字符串

ruby-on-rails - 参数错误 : invalid radix -1

mysql - 如何从 MySQL 表中的多个列中获取指定最小长度的所有不同单词?