简体   繁体   English

如何使用Ruby在文本文件中搜索完全匹配的字符串?

[英]How to search for exact matching string in a text file using Ruby?

I generated a text file having HTTP Request Response headers with response body. 我生成了一个文本文件,该文件具有带有响应主体的HTTP请求响应标头。 I want to search inside this file looking for response headers containing Access-Control-Allow-Origin: * as a header. 我想在此文件中搜索以查找包含Access-Control-Allow-Origin: *作为标题的响应标题。

The file contains this in the form of a line starting with -> and ending with " like this: 该文件以->开头并以"结尾的行的形式包含此内容,如下所示:

-> "Access-Control-Allow-Origin: *\r\n"

How can I search this text file and print a custom message above the request response headers using an if condition? 如何使用if条件搜索此文本文件并在请求响应标题上方打印自定义消息?

Do I need some complex regex? 我需要一些复杂的正则表达式吗?

With my code I can not get the correct search: 使用我的代码,我无法获得正确的搜索:

require 'net/http'
require 'uri'
require 'IPAddr'
require 'timeout'

puts "Origin IP:\n\n"
originip = gets()
puts "Start IP:\n\n"
startip = gets()
puts "End IP:\n\n"
endip = gets()
(IPAddr.new("#{startip}")..IPAddr.new("#{endip}")).each do |address|
  begin
   uri = URI("http://#{address.to_s}")
   http = Net::HTTP.new(uri.host, uri.port)
   http.set_debug_output($stdout)
   request = Net::HTTP::Get.new(uri.request_uri)
   request.initialize_http_header({"Origin" => "#{originip}"})
   response = http.request request
   $stdout.reopen('Access-Control-Allow-Origin.txt','a')
   f = File.Open('Access-Control-Allow-Origin.txt')
   line = f.read
   if line = /Access-Control-Allow-Origin: */ then
     puts "\n\nAccess-Control-Allow-Origin: * Header Found:\n\n"
   else
     puts "\n\nAccess-Control-Allow-Origin: * Header Not Found:\n\n"
   end
 rescue Timeout::Error => exc
   puts "ERROR: #{exc.message}"
 rescue Errno::ETIMEDOUT => exc
   puts "ERROR: #{exc.message}"
 rescue Exception => exc
   puts "ERROR: #{exc.message}"
 end
end

您的if语句使用了错误的运算符。

if  line =~ /Access-Control-Allow-Origin: */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM