Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.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
ruby正则表达式扫描与=~_Ruby_Regex - Fatal编程技术网

ruby正则表达式扫描与=~

ruby正则表达式扫描与=~,ruby,regex,Ruby,Regex,Ruby(1.9.3)文档似乎暗示scan等同于=~除了 scan返回多个匹配项,而=~只返回第一个匹配项,并且 scan返回匹配数据,而=~返回索引 但是,在下面的示例中,这两个方法似乎为相同的字符串和表达式返回不同的结果。为什么呢 1.9.3p0 :002 > str = "Perl and Python - the two languages" => "Perl and Python - the two languages" 1.9.3p0 :008 > exp =

Ruby(1.9.3)文档似乎暗示scan等同于=~除了

  • scan返回多个匹配项,而=~只返回第一个匹配项,并且
  • scan返回匹配数据,而=~返回索引 但是,在下面的示例中,这两个方法似乎为相同的字符串和表达式返回不同的结果。为什么呢

    1.9.3p0 :002 > str = "Perl and Python - the two languages"
     => "Perl and Python - the two languages" 
    1.9.3p0 :008 > exp = /P(erl|ython)/
     => /P(erl|ython)/ 
    1.9.3p0 :009 > str =~ exp
     => 0 
    1.9.3p0 :010 > str.scan exp
     => [["erl"], ["ython"]] 
    
    如果第一个匹配的索引是0,那么扫描是否应该返回“Perl”和“Python”,而不是“erl”和“Python”


    谢谢

    当给定正则表达式而不捕获组时,
    scan
    将返回一个字符串数组,其中每个字符串表示正则表达式的匹配项。如果使用
    scan(/P(?:erl | ython)/)
    (与正则表达式相同,只是没有捕获组),您将得到
    [“Perl”,“Python”]
    ,这就是您所期望的


    但是,当给定带有捕获组的正则表达式时,
    scan
    将返回一个数组数组,其中每个子数组包含给定匹配的捕获。因此,如果您有例如regex
    (\w*):(\w*)
    ,您将得到一个数组数组,其中每个子数组包含两个字符串:冒号前的部分和冒号后的部分。在您的示例中,每个子数组都包含一个字符串:由
    (erl | ython)

    匹配的部分,谢谢,所以当涉及到组时,scan严格地不等同于=~,并且由于scan返回的值与=~,完全不同,所以我认为说它们是等价的并不准确。扫描返回的第一个结果将是从索引
    str=~exp
    开始的子字符串,当且仅当
    exp
    不包含捕获组时。除此之外,如果不包含捕获组,您还可以说第一个结果将等价于执行
    str=~exp
    后的
    Regexp.last\u match.string
    获取,如果它确实包含捕获组,则等价于
    Regexp.last\u match.captures
    。很高兴看到这样的帖子,您确实可以学习从…起