Mad*_*han 116 ruby regex string substring
如何从Ruby中的字符串中提取子字符串?
例:
String1 = "<name> <substring>"
Run Code Online (Sandbox Code Playgroud)
我想提取substring从String1(即最后一次出现内的一切<和>).
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
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)