Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 从较长的字符串中提取字符串| Ruby_Regex_Ruby - Fatal编程技术网

Regex 从较长的字符串中提取字符串| Ruby

Regex 从较长的字符串中提取字符串| Ruby,regex,ruby,Regex,Ruby,我正在尝试使用Ruby从长字符串中提取一个句子 例如: 您好,文件位于以下目录中:/Volumes/GAW-FS01/08\u Video/02\u Projects/Plus/S/metadata.xml谢谢您的查询 它应该返回:/Volumes/GAW-FS01/08_Video/02_Projects/Plus/S/metadata.xml 开头总是包含“/Volume”,并且以“.xml”结尾 谢谢你你可能在找这个- long_string = <<file Hi There

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

例如:

您好,文件位于以下目录中:/Volumes/GAW-FS01/08\u Video/02\u 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") }

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

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"
更有趣的是,找到字符串的索引并使用范围返回所需的字符串

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"
不那么奇怪,将字符串按起点和终点拆分,然后返回所需的字符串

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不匹配的正则表达式。

欢迎使用SO!请在代码中提供一个尝试。那么基本上
字符串[%r[/Volumes/*/\.xml]]