2012-04-24 6 views
2

ここでは、複数の正規表現評価を必要とするが、何をしたいのかを取得する(テキスト以外のすべてを削除する)1つの出力を示します。Rubyで複数の正規表現評価を避けるために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 

そして、これが唯一の最初の文を取得します。試合ではなくGSUBに(空白と非単語の文字を除去を含む)、同じ出力を得る上

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. 

任意の提案を?あなたは1回のGSUB操作でやりたいことができ

答えて

1

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

Thanks Hck。私はそれを得たと思う。これは空白文字(\ s)、ピリオド(。)、疑問符(?)を評価し、何も置き換えません。役に立ったちょうど正規表現のハング取得に取り組む必要があります。 – drollwit

0

このため、複数の正規表現の評価を必要としません。

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

入手しました。単語以外の文字(\ W)を何も置き換えないでください( "")。 OK、正式に通知。私はこれを分析しなければなりません!ありがとう。 – drollwit

関連する問題