使用正则表达式从 Ruby 中的字符串中提取子字符串 [英] Extract a substring from a string in Ruby using a regular expression

查看:55
本文介绍了使用正则表达式从 Ruby 中的字符串中提取子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 Ruby 中的字符串中提取子字符串?

How can I extract a substring from within a string in Ruby?

示例:

String1 = "<name> <substring>"

我想从 String1 中提取 substring(即 <> 最后一次出现的所有内容>).

I want to extract substring from String1 (i.e. everything within the last occurrence of < and >).

推荐答案

String1.scan(/<([^>]*)>/).last.first

scan 创建一个数组,对于 String1 中的每个 包含 < 之间的文本code> 和 > 在单元素数组中(因为当与包含捕获组的正则表达式一起使用时, scan 创建一个包含每个匹配项的捕获的数组).last 为您提供这些数组中的最后一个,first 然后为您提供其中的字符串.

scan creates an array which, for each <item> in String1 contains the text between the < and the > in a one-element array (because when used with a regex containing capturing groups, scan creates an array containing the captures for each match). last gives you the last of those arrays and first then gives you the string in it.

这篇关于使用正则表达式从 Ruby 中的字符串中提取子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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