使用正则expression式从Ruby中的string中提取子string
如何从Ruby中的string中提取一个子string?
例:
String1 = "<name> <substring>"
我想从String1提取substring (即最后一个<和> )。
String1.scan( /<([^>]*)>/).last.first
scan创build一个数组,该数组对每个<item>在String1包含一个元素数组中的<和>之间的文本(因为当与包含捕获组的正则expression式一起使用时,scan会创build一个包含每个匹配捕获的数组) 。 last给你这些数组的最后first然后给你的string中。
"<name> <substring>"[/.*<([^>]*)/,1] => "substring"
如果我们只需要一个结果就不需要使用scan 。
没有必要使用match ,当我们有String[regexp,#] 。
请参阅: http : //ruby-doc.org/core/String.html#method-i-5B-5D
注意: str[regexp, capture] → new_str or nil
你可以很容易地使用正则expression式…
允许在单词旁边的空格(但不保留它们):
str.match(/< ?([^>]+) ?>\Z/)[1]
或者没有允许的空间:
str.match(/<([^>]+)>\Z/)[1]
这是一个比较灵活的使用match方法的方法。 有了这个,你可以提取多个string:
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