加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby one-liner用于捕获正则表达式匹配

发布时间:2020-12-17 04:23:34 所属栏目:百科 来源:网络整理
导读:在Perl中,我使用以下一行语句通过正则表达式从字符串中提取匹配项并分配它们.这个找到一个匹配并将其分配给一个字符串: my $string = "the quick brown fox jumps over the lazy dog.";my $extractString = ($string =~ m{fox (.*?) dog})[0]; 结果:$extra
在Perl中,我使用以下一行语句通过正则表达式从字符串中提取匹配项并分配它们.这个找到一个匹配并将其分配给一个字符串:
my $string = "the quick brown fox jumps over the lazy dog.";

my $extractString = ($string =~ m{fox (.*?) dog})[0];

结果:$extractString ==’跳过懒惰’

这个从多个匹配创建一个数组:

my $string = "the quick brown fox jumps over the lazy dog.";

my @extractArray = $string =~ m{the (.*?) fox .*?the (.*?) dog};

结果:@extractArray == [‘quick brown’,’lazy’]

是否有相同的方法在Ruby中创建这些单行?

解决方法

string = "the quick brown fox jumps over the lazy dog."

extract_string = string[/fox (.*?) dog/,1]
# => "jumps over the lazy"

extract_array = string.scan(/the (.*?) fox .*?the (.*?) dog/).first
# => ["quick brown","lazy"]

如果未找到匹配项,此方法也将返回nil(而不是抛出错误).

extract_string = string[/MISSING_CAT (.*?) dog/,1]
# => nil

extract_array = string.scan(/the (.*?) MISSING_CAT .*?the (.*?) dog/).first
# => nil

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读