Ruby 如何计算正则表达式结束的位置?

Ruby 如何计算正则表达式结束的位置?,ruby,regex,string,position,Ruby,Regex,String,Position,使用Ruby 2.4。如果我想找出正则表达式在字符串中出现的位置,我可以这样做 2.4.0 :014 > line = "1 a b c d" => "1 a b c d" 2.4.0 :015 > string_tokens = ["a", "b", "c", "d"] => ["a", "b", "c", "d"] 2.4.0 :025 > first_pos = line.index( /#{string_tokens.join("

使用Ruby 2.4。如果我想找出正则表达式在字符串中出现的位置,我可以这样做

2.4.0 :014 > line = "1 a b     c d"
 => "1 a b     c d" 
2.4.0 :015 > string_tokens = ["a", "b", "c", "d"]
 => ["a", "b", "c", "d"] 

2.4.0 :025 > first_pos = line.index( /#{string_tokens.join(" ").gsub(" ", "\s+")}/ )
 => 7
但是如何确定正则表达式在字符串中的结束位置呢

line = "1 a b     c d"
string_tokens = ["a", "b", "c", "d"]
我相信OP的目的是形成如下正则表达式

r = /#{string_tokens.join('\s+')}/
  #=> /a\s+b\s+c\s+d/
然后

告诉我们在
行的偏移量
2
处有一个匹配开始。要找到比赛的终点,我们可以使用以下方法之一

第一条路

(line =~ r) + line[r].size - 1
  #=> 12
作为

第二种方式

(line =~ r) + line[r].size - 1
  #=> 12
这使用和

LastMatchend(n)
返回“字符串中匹配数组第n个元素末尾之后的字符偏移量”。因此,需要
-1

line[r]
  #=> "a b     c d" 
line =~ r
  #=> 2

Regexp.last_match.end(0)-1
  #=> 12