如何从扫描和拆分中获得结果字符串 - 正面和负面匹配?相当于
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]]
答案 0 :(得分: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."]]