2

如何从字符串中获取扫描和拆分结果 - 正匹配和负匹配?相当于

def scan_and_split(string, regexp)
  string.split(regexp).zip(string.scan(regexp))
end

scan_and_split("{T}: Add {W} or {U} to your mana pool. Adarkar Wastes deals 1 damage to you.", /\{[^ ]+\}/)

预期输出:

[["", "{T}"], [": Add ", "{W}"], [" or ", "{U}"], [" to your mana pool. Adarkar Wastes deals 1 damage to you.", nil]]
4

1 回答 1

1

split与捕获一起使用。

"ababab".split(/(a)/)
# => ["", "a", "b", "a", "b", "a", "b"]

"{T}: Add {W} or {U} to your mana pool. Adarkar Wastes deals 1 damage to you.".split(/(\{[^ ]+\})/)
# => ["", "{T}", ": Add ", "{W}", " or ", "{U}", " to your mana pool. Adarkar Wastes deals 1 damage to you."]

如果您想要每个split/的子数组match,则应用于each_slice(2).to_a结果。

"ababab".split(/(a)/).each_slice(2).to_a
# => [["", "a"], ["b", "a"], ["b", "a"], ["b"]]

"{T}: Add {W} or {U} to your mana pool. Adarkar Wastes deals 1 damage to you.".split(/(\{[^ ]+\})/).each_slice(2).to_a
# => [["", "{T}"], [": Add ", "{W}"], [" or ", "{U}"], [" to your mana pool. Adarkar Wastes deals 1 damage to you."]]
于 2012-11-27T07:52:13.637 回答