使用 ruby 在字符串中提取路径

extracting path within a string using ruby

我编写了一个 ruby 脚本,我在其中遍历文件夹,并搜索以 ".xyz" 结尾的文件名。然后在这些文件中搜索具有以下结构的行:

<ClCompile Include="..\..\..\Projects\Project_A\Applications\Modules\Sources\myfile.c"/>

到目前为止,这适用于脚本:

def parse_xyz_files
  files = Dir["./**/*.xyz"]
  files.each do |file_name|
    puts file_name
    File.open(file_name) do |f|
      f.each_line { |line|
        if line =~ /<ClCompile Include=/
          puts "Found #{line}"
        end 
      }
  end
  end
  end

现在我只想提取双引号之间的字符串,在这个例子中:

..\..\..\Projects\Project_A\Applications\Modules\Sources\myfile.c

我正在尝试用这样的方法(使用匹配方法):

def parse_xyz_files
  files = Dir["./**/*.xyz"]
  files.each do |file_name|
    puts file_name
    File.open(file_name) do |f|
      f.each_line { |line|
        if line =~ /<ClCompile Include=/.match(/"([^"]*)"/)
            puts "Found #{line}"
          end

      }
  end
  end
  end

到目前为止,正则表达式没问题(用 rubular 检查)。知道如何以简单的方式做到这一点吗?我对 ruby 比较陌生。

您可以使用String#scan方法:

line = '<ClCompile Include="..\..\..\Projects\Project_A\Applications\Modules\Sources\myfile.c"/>'

path = line.scan(/".*"/).first

或者如果您的 <CICompile> 标签可以有一些其他属性,那么:

path = line.scan(/Include="(.*)"/).first.first

但是使用 XML 解析器绝对是一个更好的主意。

使用 Nokogiri 解析 XML 而不是正则表达式。

require 'nokogiri'
xml = '<foo><bar><ClCompile Include="..\..\..\Projects\Project_A\Applications\Modules\Sources\myfile.c"/></bar></foo>'
document = Nokogiri::XML xml
d.xpath('//ClCompile/@Include').text