“他说”,ruby-on-rails,ruby,regex,Ruby On Rails,Ruby,Regex" /> “他说”,ruby-on-rails,ruby,regex,Ruby On Rails,Ruby,Regex" />

Ruby on rails 正则表达式初学者 def showRE(a,re) 如果a=~re "#{$`}#{$'}" 其他的 “不匹配” 终止 终止 showRE('他说'你好',/([“'])。?\1/) #=>“他说”

Ruby on rails 正则表达式初学者 def showRE(a,re) 如果a=~re "#{$`}#{$'}" 其他的 “不匹配” 终止 终止 showRE('他说'你好',/([“'])。?\1/) #=>“他说”,ruby-on-rails,ruby,regex,Ruby On Rails,Ruby,Regex,有人能解释一下为什么这个函数返回“Hello”。更具体地说,*?\的用途以及它如何导致函数返回它的功能。我知道[“]找到“/”或“/”,并且\1指的是第一组的匹配项。但是不应该返回->“他说Hello”'因为“/”是表示括号中内容的字符串的第一行 作为参数传递的正则表达式(我将以“自由间距”模式编写,以使其能够自我记录),如下所示: def showRE(a,re) if a =~ re "#{$`}<<#{$&}>>#{$'}" else

有人能解释一下为什么这个函数返回“Hello”。更具体地说,*?\的用途以及它如何导致函数返回它的功能。我知道[“]找到“/”或“/”,并且\1指的是第一组的匹配项。但是不应该返回->“他说Hello”'因为“/”是表示括号中内容的字符串的第一行

作为参数传递的正则表达式(我将以“自由间距”模式编写,以使其能够自我记录),如下所示:

def showRE(a,re)
  if a =~ re
    "#{$`}<<#{$&}>>#{$'}"
  else
    "no match"
  end
end

showRE('He said "Hello"', /(["']).*?\1/)
  #=> "He said <<\"Hello\">>"
由于
str=~r
是“真实的”,我们评估

r = /
    (      # start capture group 1
    ["']   # match a double or single parenthesis (a "character class")
    )      # end capture group 1
    .*     # match zero or more (`*`) characters (any characters)
    ?      # make the foregoing match (.*) lazy
    \1     # match the contents of capture group 1
    /x     # free-spacing regex definition mode

str = 'He said "Hello"'
  #=> "He said \"Hello\""
str =~ r
  #=> 8 (we have a match beginning at str[8])
中给出了这些变量的含义。你会看到:

  • $`包含上次成功匹配左侧的字符串
  • $&包含上次成功匹配的字符串;及
  • $包含上次成功匹配右侧的字符串
所以我们有(并返回)


我说不出为什么正则表达式中的匹配项
*
被设置为惰性(通过将其设置为
*?
)。

这个缩进实际上是无政府状态的。你能清理一下吗?它有助于我们理解您试图做什么。一个好的例子可以帮助说明正则表达式正在做什么。除非这是一个好办法。如果任何一个答案都是有用的,请考虑选择一个。真的令人印象深刻。
"#{$`}<<#{$&}>>#{$'}"
   => "He said <<\"Hello\">>"
$` #=> "He said "
$& #=> "\"Hello\""
$' #=> ""
"#{"He said "}<<#{"\"Hello\""}>>#{""}"
  #=> => "He said <<\"Hello\">>"
last_match = Regexp.last_match
  #=> #<MatchData "\"Hello\"" 1:"\"">
last_match.pre_match  #=> "He said "
last_match[0]         #=> "\"Hello\""
last_match.post_match #=> ""