Reactormonk
Reactormonk

Reputation: 21730

scan and split a string

How can I get the results from both scan and split form a string - positive and negative matches? Equivalent to

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.", /\{[^ ]+\}/)

Expected output:

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

Upvotes: 2

Views: 367

Answers (1)

sawa
sawa

Reputation: 168199

Use split with captures.

"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."]

If you want a subarray for each split/match, then apply each_slice(2).to_a to the result.

"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."]]

Upvotes: 1

Related Questions