返回 Ruby 正则表达式的第一个匹配项 [英] Return first match of Ruby regex

查看:37
本文介绍了返回 Ruby 正则表达式的第一个匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在 Ruby 中对字符串执行正则表达式匹配并在第一次匹配时使其短路的方法.

I'm looking for a way to perform a regex match on a string in Ruby and have it short-circuit on the first match.

我正在处理的字符串很长,从它看起来的标准方式(match 方法)可以处理整个事情,收集每个匹配项,并返回一个包含所有匹配项的 MatchData 对象.

The string I'm processing is long and from what it looks like the standard way (match method) would process the whole thing, collect each match, and return a MatchData object containing all matches.

match = string.match(/regex/)[0].to_s

推荐答案

你可以试试 String#[](如variableName[/regular expression/]).

这是来自 IRB 的示例输出:

This is an example output from IRB:

names = "erik kalle johan anders erik kalle johan anders"
# => "erik kalle johan anders erik kalle johan anders"
names[/kalle/]
# => "kalle"

这篇关于返回 Ruby 正则表达式的第一个匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆