如何从Ruby中的字符串中提取一个子字符串?
示例:
String1 = "<name> <substring>"
我想从String1
中提取substring
(即最后一次出现的<
和>
中的所有内容)。
发布于 2010-11-07 04:58:12
String1.scan(/<([^>]*)>/).last.first
scan
创建一个数组,对于String1
中的每个<item>
,该数组在一个元素数组中包含<
和>
之间的文本(因为当与包含捕获组的正则表达式一起使用时,scan会创建一个包含每个匹配的捕获的数组)。last
会给出最后一个数组,然后first
会给出其中的字符串。
发布于 2010-11-07 05:00:26
"<name> <substring>"[/.*<([^>]*)/,1]
=> "substring"
如果我们只需要一个结果,就不需要使用scan
。
当我们有Ruby的String[regexp,#]
时,不需要使用Python的match
。
请参阅:http://ruby-doc.org/core/String.html#method-i-5B-5D
注:str[regexp, capture] → new_str or nil
发布于 2010-11-07 04:59:20
您可以使用正则表达式来实现非常简单的…
允许单词周围有空格(但不保留空格):
str.match(/< ?([^>]+) ?>\Z/)[1]
或者不使用允许的空格:
str.match(/<([^>]+)>\Z/)[1]
https://stackoverflow.com/questions/4115115
复制相似问题