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