检查文本文件中是否存在所需的值对

时间:2017-09-07 08:12:48

标签: ruby

我有一个文本文件,其数据如下所示:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context="com.app.myapplication.FunctionSelection">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="TextView" />

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="?android:attr/windowBackground"
        app:menu="@menu/navigation" />


    <FrameLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_marginTop="?android:attr/actionBarSize"
        android:layout_height="match_parent">

    </FrameLayout>


</LinearLayout>

也就是说,我有var1="something1" var2="some432543" var1="something2" var2="somethifdsng22dsf" var1="some3223423" var2="somethifdsng22dsf" var1="somet76598764322==-" var2="som@fds2002)02-" # and so on.... var1对的列表。我想查找是否存在具有特定值var2 / var1的货币对。我可以像var2那样执行此操作:

var1

但这只是我需要的一半。什么是检查 value1 = "somet76598764322==-" value2 = "som@fds2002)02-" f1 = File.readlines("my_file.txt") # find var1 exists = f1.grep(/var1=\"#{value1}\"/).size > 0 if exists # what about var2??? end var1的合适方式?

2 个答案:

答案 0 :(得分:0)

这应该有效:

  # the second value is the only one that needs to be escaped,
  # but doing it to both doesn't hurt
  var1= Regexp.escape "somet76598764322==-"
  var2= Regexp.escape "som@fds2002)02-"

  # use read not readlines since you want to match across multiple lines
  f1 = File.read("my_file.txt")

  # add a \n and the second var to the regex
  exists = x.scan(/var1=\"#{var1}\"\nvar2=\"#{var2}\"/).empty?

答案 1 :(得分:0)

value1, value2 = ['var1="somet76598764322==-"', 'var2="som@fds2002)02-"']
File.readlines('my_file.txt')
    .each_slice(3)
    .map { |arr| arr.map(&:strip) }
    .detect do |var1, var2, _|
  [var1, var2] == [value1, value2]
end
#⇒ [
#   [0] "var1=\"somet76598764322==-\"",
#   [1] "var2=\"som@fds2002)02-\""
# ]

这比grep效率更高,因为它仅在输入中传递一次并在找到匹配后立即停止。