开发者

stdin doesnt work ruby

开发者 https://www.devze.com 2023-02-24 02:18 出处:网络
I have the following script: $stdin.each_line do |data| blocks = data.scan(/\\+[^+]+\\+/) blocks.reject! { |b| b.include? \"AAAAAAAAA\" }

I have the following script:

$stdin.each_line do |data|    
  blocks = data.scan(/\+[^+]+\+/)
  blocks.reject! { |b| b.include? "AAAAAAAAA" }    
  p blocks    
end

This script will remove that开发者_JAVA百科 string of A's in a stdin file. I have two questions:

  1. The stdin doesnt seem to work, it outputs [].
  2. How can I modify the script to say that reject a stretch of single letters that have length 20 or above, so if there is a stretch of 20 or more A's, remove the block.


To reject all blocks with 20 or more identical uppercase characters:

$stdin.each_line do |data|
  blocks = data.scan(/\+[^+]+\+/)
  ('A'..'Z').each do |ch|
    r = Regexp.new("[" + ch + "]{20,}")
    blocks.reject! { |b| r =~ b }
  end
  p blocks
end

This builds 26 regexes (one for each uppercase character) and matches blocks against them.
Of course, it would be much more efficient to build them just once and store them in an array or similar instead of rebuilding them for each line in the input.

A more compact solution:

  r = /([a-z])\1{19,}/
  $stdin.each_line do |data|
      blocks = data.scan(/\+[^+]+\+/)
      blocks.reject! { |b| r =~ b }
      p blocks
  end

This one uses a single regular expression to match a single character, and 19 or more occurences of the same character directly afterwards (using a back reference).


The regular expression for your reject! statement is:

/([A-Z])\1{19}/

This matches any capital letter followed by 19 more of the exact same letter.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号