2009-03-29 50 views
1

「検索結果:16143件見つかりました」という文字列があり、その中から16143文字を取り出す必要があります。正規表現を使用して文字列パターンから数字を取得

私はRubyでコーディングしていると私は、これはそれが私がRubyでこの文字列から番号を取得する方法を正規表現(区切り文字に基づいて分割文字列に反対するとして)

を使用して取得するクリーンだろう知っていますか?

+0

あなたは数が非negatになると確信しています数字以外の数字は含まれず、指数表記になりませんか? –

答えて

2

私はRubyで構文上のわからないんだけど、正規表現は次のようになります「(\ D +)」サイズ1かの数字の文字列を意味しますもっと。あなたはここでそれを試してみることができます。http://www.rubular.com/

更新: を私は構文が/(\d+)/.match(your_stringされると信じて)

+0

括弧で囲まれた\ d +は、実際には一致と比較して真または偽を返すのではなく、値をキャプチャすることに注意してください。 – LaserJesus

+0

整数に変換することを忘れないでください(Integer(foo)もfoo.to_iも完全ではありません。あなたが*それが数字であることを知っているならば、私はto_iを提案するでしょう)。 –

1

この正規表現は、それを行う必要があります。

\d+ 
1

非正規表現のアプローチについて:

irb(main):001:0> foo = "Search result:16143 Results found" 
=> "Search result:16143 Results found" 
irb(main):002:0> foo[foo.rindex(':')+1..foo.rindex(' Results')-1] 
=> "16143" 
1
# check that the string you have matches a regular expression 
if foo =~ /Search result:(\d+) Results found/ 
    # the first parenthesized term is put in $1 
    num_str = $1 
    puts "I found #{num_str}!" 
    # if you want to use the match as an integer, remember to use #to_i first 
    puts "One more would be #{num_str.to_i + 1}!" 
end 
8
> foo = "Search result:16143 Results found" 
=> "Search result:16143 Results found" 
> foo[/\d+/].to_i 
=> 16143 
+0

これは正規表現パターンに基づいて文字列から抽出するのに好ましい方法です。 – Sim

0
> foo = "Search result:16143 Results found" 
=> "Search result:16143 Results found" 
> foo.scan(/\d/).to_i 
=> 16143