使用正则表达式从Ruby中的字符串中提取子字符串

Mad*_*han 116 ruby regex string substring

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

例:

String1 = "<name> <substring>"
Run Code Online (Sandbox Code Playgroud)

我想提取substringString1(即最后一次出现内的一切<>).

Nak*_*lon 297

"<name> <substring>"[/.*<([^>]*)/,1]
=> "substring"
Run Code Online (Sandbox Code Playgroud)

scan如果我们只需要一个结果,则无需使用.
没必要用match,当我们有String[regexp,#].

请参阅:http://ruby-doc.org/core/String.html#method-i-5B-5D

注意: str[regexp, capture] ? new_str or nil

  • @coreyward,如果他们更好,拜托,争论吧.例如,sepp2k的解决方案更灵活,这就是为什么我在我的解决方案中指出`如果我们只需要一个结果`.并且`match()[]`比较慢,因为它是两种方法而不是一种方法. (39认同)
  • 无需诋毁其他完全有效的(并且可能是我的,更可读的)解决方案. (36认同)
  • 是的......让这个功能慢2倍......他们的孩子也有功能......父母也是......他们太快了,以至于我们永远都不会注意到他们......采取规则*不要害怕使功能慢2倍!*......什么?我们的10个函数链现在慢了1024倍?梦幻般的... (8认同)
  • 我觉得这个解决方案更简单直观(因为我是Ruby新手).谢谢. (8认同)
  • 这是所有方法中速度最快的,但即使是最慢的方法,我的机器也只需4.5微秒.我不在乎推测为什么这种方法更快.在表现中,猜测是_useless_.仅测量计数. (4认同)

sep*_*p2k 122

String1.scan(/<([^>]*)>/).last.first
Run Code Online (Sandbox Code Playgroud)

scan创建其中,对于每个阵列<item>String1包含的文本<和所述>一个元素阵列中的(因为与含有捕获组正则表达式中使用时,扫描创建包含每个匹配的捕获阵列).last为您提供最后一个数组,first然后为其提供字符串.


cor*_*ard 22

您可以非常轻松地使用正则表达式...

允许单词周围的空格(但不保留它们):

str.match(/< ?([^>]+) ?>\Z/)[1]
Run Code Online (Sandbox Code Playgroud)

或者没有允许的空格:

str.match(/<([^>]+)>\Z/)[1]
Run Code Online (Sandbox Code Playgroud)


Gra*_*ier 10

这是使用该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"
Run Code Online (Sandbox Code Playgroud)


小智 7

更简单的扫描是:

String1.scan(/<(\S+)>/).last
Run Code Online (Sandbox Code Playgroud)