如何解决从更长的字符串中提取字符串|红宝石
我正在尝试使用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”
谢谢
解决方法
您可能正在寻找-
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") }
它将为您提供一系列符合条件的路径,例如Follow-
["/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"]
,
有很多方法可以做到这一点。
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之间变化,您仍然注意到first和last选项是相同的。0捕获用于匹配1的正则表达式。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。