字符串上的扫描和匹配有什么区别

字符串上的扫描和匹配有什么区别

本文介绍了Ruby 字符串上的扫描和匹配有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Ruby 的新手,一直使用 String.scan 来搜索第一次出现的数字.返回值在嵌套数组中有点奇怪,但我只是去 [0][0] 我想要的值.(我确定它有它的用途,只是我还没有使用它.)

I am new to Ruby and has always used String.scan to search for the first occurrence of a number. It is kind of strange that the returned value is in nested array, but I just go [0][0] for the values I want. (I am sure it has its purpose, just that I haven't used it yet.)

我刚刚发现有一个 String.match 方法.而且似乎更方便,因为返回的数组不是嵌套的.

I just found out that there is a String.match method. And it seems to be more convenient because the returned array is not nested.

这里是两者的例子,首先是扫描:

Here is an example of the two, first is scan:

>> 'a 1-night stay'.scan(/(a )?(\d*)[- ]night/i).to_a
=> [["a ", "1"]]

然后是匹配

>> 'a 1-night stay'.match(/(a )?(\d*)[- ]night/i).to_a
=> ["a 1-night", "a ", "1"]

我已经检查了 API,但我无法真正区分差异,因为两者都称为匹配模式".

I have check the API, but I can't really differentiate the difference, as both referred to 'match the pattern'.

这个问题只是出于好奇,关于 scan 可以做什么而 match 不能,反之亦然.只有一个人可以完成的特定场景吗?matchscan的劣势?

This question is, for simply out curiousity, about what scan can do that match can't, and vise versa. Any specific scenario that only one can accomplish? Is match the inferior of scan?

推荐答案

简短回答:scan 将返回所有匹配项.这并没有让它变得更好,因为如果你只想要第一个匹配,str.match[2] 读起来比 str.scan[0][1] 好得多.

Short answer: scan will return all matches. This doesn't make it superior, because if you only want the first match, str.match[2] reads much nicer than str.scan[0][1].

ruby-1.9.2-p290 :002 > 'a 1-night stay, a 2-night stay'.scan(/(a )?(\d*)[- ]night/i).to_a
 => [["a ", "1"], ["a ", "2"]]
ruby-1.9.2-p290 :004 > 'a 1-night stay, a 2-night stay'.match(/(a )?(\d*)[- ]night/i).to_a
 => ["a 1-night", "a ", "1"]

这篇关于Ruby 字符串上的扫描和匹配有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 04:50