贪婪匹配

当一个字符串包含多个潜在的匹配值时,你有时可能希望该字符串返回第一个匹配项(即,尽可能少的字符串与匹配模式一致),并且在其它时候你可能希望该字符串返回一直到最后一个匹配项(也就是尽可能多的字符串)。

在后一种情况下(获得尽可能多的字符串),这中匹配被称为“贪婪的”(greedy)。*+ 模式量词是贪婪的。你可以通过在其后放置 ? 让它们节制一点,以使它们尽可能少地返回匹配值:

greedy1.rb
  1. puts( /.*at/.match('The cat sat on the mat!') ) #=> returns: The cat sat on the mat
  2. puts( /.*?at/.match('The cat sat on the mat!') ) #=> returns: The cat

你可以控制模式匹配的贪婪性,以执行诸如处理目录路径之类的操作:

greedy2.rb
  1. puts( /.+\\/.match('C:\mydirectory\myfolder\myfile.txt') ) #=> C:\mydirectory\myfolder\
  2. puts( /.+?\\/.match('C:\mydirectory\myfolder\myfile.txt') ) #=> C:\