[ruby] Ruby의 문자열에서 숫자 추출

이 코드를 사용하고 있습니다.

s = line.match( /ABCD(\d{4})/ ).values_at( 1 )[0]

다음과 같은 문자열에서 숫자를 추출하려면

ABCD1234
ABCD1235
ABCD1236

기타

작동하지만 Ruby에서 이것에 대한 다른 대안이 무엇인지 궁금합니다.

내 코드 :

ids = []
someBigString.lines.each {|line|
   ids << line.match( /ABCD(\d{4})/ ).values_at( 1 )[0]
}



답변

a.map {|x| x[/\d+/]}


답변

http://www.ruby-forum.com/topic/125709에 따라 많은 Ruby 방법이 있습니다 .

  1. line.scan(/\d/).join('')
  2. line.gsub(/[^0-9]/, '')
  3. line.gsub(/[^\d]/, '')
  4. line.tr("^0-9", '')
  5. line.delete("^0-9")
  6. line.split(/[^\d]/).join
  7. line.gsub(/\D/, '')

콘솔에서 각각을 시도하십시오.

해당 게시물의 벤치 마크 보고서도 확인하십시오.


답변

더 간단한 해결책이 있습니다

line.scan(/\d+/).first


답변

가장 간단하고 빠른 방법은 문자열에서 모든 정수를 가져 오는 것입니다.

str = 'abc123def456'

str.delete("^0-9")
=> "123456"

여기에 제공된 다른 솔루션과 긴 문자열에 대한 벤치 마크를 비교하면 이것이 훨씬 더 빠르다는 것을 알 수 있습니다.

require 'benchmark'

@string = [*'a'..'z'].concat([*1..10_000].map(&:to_s)).shuffle.join

Benchmark.bm(10) do |x|
  x.report(:each_char) do
    @string.each_char{ |c| @string.delete!(c) if c.ord<48 or c.ord>57 }
  end
  x.report(:match) do |x|
    /\d+/.match(@string).to_s
  end
  x.report(:map) do |x|
    @string.split.map {|x| x[/\d+/]}
  end
  x.report(:gsub) do |x|
    @string.gsub(/\D/, '')
  end
  x.report(:delete) do
    @string.delete("^0-9")
  end
end

             user     system      total        real
each_char    0.020000   0.020000   0.040000 (  0.037325)
match        0.000000   0.000000   0.000000 (  0.001379)
map          0.000000   0.000000   0.000000 (  0.001414)
gsub         0.000000   0.000000   0.000000 (  0.000582)
delete       0.000000   0.000000   0.000000 (  0.000060)


답변

your_input = "abc1cd2"
your_input.split(//).map {|x| x[/\d+/]}.compact.join("").to_i

작동합니다.


답변

또 다른 해결책은 다음과 같이 작성하는 것입니다.

myString = "sami103"
myString.each_char{ |c| myString.delete!(c) if c.ord<48 or c.ord>57 } #In this case, we are deleting all characters that do not represent numbers.

이제 입력하면

myNumber = myString.to_i #or myString.to_f

이것은


답변

문자열에서 숫자 부분을 추출하려면 다음을 사용하십시오.

str = 'abcd1234'
/\d+/.match(str).try(:[], 0)

반환되어야합니다 1234