簡體   English   中英

使用select而不是gsub來避免Ruby中的多個正則表達式求值

[英]Using select rather than gsub to avoid multiple regex evaluations in Ruby

這是一個輸出,需要多個正則表達式求值,但可以完成我想做的事情(刪除文本以外的所有內容)。

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:有沒有更好的方法 -我認為我將嘗試進行匹配以在沒有多個正則表達式評估的情況下完成相同的結果。 但是我沒有得到相同的輸出。

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"

您不需要為此進行多個正則表達式評估。

str = "# output - this only gets the first sentence
# When in the course of human events it becomes necessary."
p str.gsub(/\W/, "")
#=>"outputthisonlygetsthefirstsentenceWheninthecourseofhumaneventsitbecomesnecessary"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM