【问题标题】:Extract string from within a longer string | Ruby从较长的字符串中提取字符串 |红宝石
【发布时间】:2020-12-02 18:06:10
【问题描述】:

我正在尝试使用 Ruby 从长字符串中提取一个句子。

例子:

您好,该文件位于以下目录:/Volumes/GAW-FS01/08_Video/02_Projects/Plus/S/metadata.xml感谢您的询问。

它应该返回:/Volumes/GAW-FS01/08_Video/02_Projects/Plus/S/metadata.xml 开头始终包含“/Volume”,并以“.xml”结尾

谢谢

【问题讨论】:

  • 欢迎来到 SO!请提供代码尝试。
  • 所以基本上string[%r[/Volumes/.*/\.xml]]?

标签: regex ruby


【解决方案1】:

你可能正在寻找这个 -

long_string = <<file
Hi There the file is in this directory: /Volumes/GAW-FS01/08_Video/02_Projects/Plus/S/metadata.xml Thank you for your inquiry.Hi There the file is in this directory: /Volumes/GAW-def/08_Video/02_Projects/Plus/S/metadata.xml Thank you for your inquiry.Hi There the file is in this directory: /Volumes/GAW-FS01/08_Video/02_Projects/hello/S/metadata.xml Thank you for your inquiry.
file

long_string.split.select{ |word| word.starts_with?("/Volumes") && word.end_with?(".xml") }

它会为您提供与您的条件相匹配的路径数组,例如跟随 -

["/Volumes/GAW-FS01/08_Video/02_Projects/Plus/S/metadata.xml", "/Volumes/GAW-def/08_Video/02_Projects/Plus/S/metadata.xml", "/Volumes/GAW-FS01/08_Video/02_Projects/hello/S/metadata.xml"]

【讨论】:

    【解决方案2】:

    有很多方法可以做到这一点。

    string = "Hi There the file is in this directory: /Volumes/GAW-FS01/08_Video/02_Projects/ Plus/S/metadata.xml Thank you for your inquiry." 
    

    时髦:

    "Volume#{string[/Volume(.*?).xml/, 1]}.xml"
    

    Funkier,找到字符串的索引,使用范围返回想要的字符串

    first = "Volume"
    last = ".xml"
    string[(string.index(first)) .. (string.index(last) + last.length)]
     => "Volumes/GAW-FS01/08_Video/02_Projects/ Plus/S/metadata.xml "
    

    不是那么时髦,将字符串按起点和终点拆分并返回所需的字符串

    "Volume#{string.split('Volume').last.split('.xml').first}.xml"
     => "Volumes/GAW-FS01/08_Video/02_Projects/ Plus/S/metadata.xml"
    

    最后,您可能想要这样做的方式

    string[/Volume(.*?).xml/, 0]
    => "Volumes/GAW-FS01/08_Video/02_Projects/ Plus/S/metadata.xml"
    

    您注意到第一个和最后一个选项是相同的,尽管传递的 int 在 0 和 1 之间变化。0 捕获用于匹配 1 不匹配的正则表达式。

    【讨论】:

      猜你喜欢
      • 2010-11-29
      • 1970-01-01
      • 2014-02-11
      • 2011-01-21
      • 2010-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多