【发布时间】:2011-05-06 03:11:34
【问题描述】:
如何从 Ruby 中的字符串中提取子字符串?
例子:
String1 = "<name> <substring>"
我想从String1 中提取substring(即最后一次出现< 和> 中的所有内容)。
【问题讨论】:
标签: ruby regex string substring
如何从 Ruby 中的字符串中提取子字符串?
例子:
String1 = "<name> <substring>"
我想从String1 中提取substring(即最后一次出现< 和> 中的所有内容)。
【问题讨论】:
标签: ruby regex string substring
"<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
【讨论】:
if we need only one result 的原因。而match()[] 更慢,因为它是两种方法而不是一种。
string[regex] 在这种情况下同样可读,所以这就是我个人使用的。
String1.scan(/<([^>]*)>/).last.first
scan 创建一个数组,对于String1 中的每个<item>,该数组在一个元素数组中包含< 和> 之间的文本(因为当与包含捕获组的正则表达式一起使用时, scan 创建一个包含每个匹配项的捕获的数组)。 last 为您提供最后一个数组,first 然后为您提供其中的字符串。
【讨论】:
你可以很容易地使用正则表达式……
在单词周围允许空格(但不能保留):
str.match(/< ?([^>]+) ?>\Z/)[1]
或者没有空格:
str.match(/<([^>]+)>\Z/)[1]
【讨论】:
<> 实际上是否需要成为字符串中的最后一个。如果例如字符串foo <bar> baz 是允许的(并且应该给出结果bar),这是行不通的。
这是一种使用match 方法的更灵活的方法。这样,您可以提取多个字符串:
s = "<ants> <pants>"
matchdata = s.match(/<([^>]*)> <([^>]*)>/)
# Use 'captures' to get an array of the captures
matchdata.captures # ["ants","pants"]
# Or use raw indices
matchdata[0] # whole regex match: "<ants> <pants>"
matchdata[1] # first capture: "ants"
matchdata[2] # second capture: "pants"
【讨论】:
更简单的扫描是:
String1.scan(/<(\S+)>/).last
【讨论】: