This commit is contained in:
Ingy döt Net 2013-04-10 21:29:02 -07:00
parent 764da6cbbb
commit db842d013d
19005 changed files with 197040 additions and 7 deletions

View file

@ -0,0 +1,14 @@
text = 'a!===b=!=c'
separators = ['==', '!=', '=']
def multisplit_simple(text, separators)
sep_regex = Regexp.new(separators.collect {|sep| Regexp.escape(sep)}.join('|'))
text.split(sep_regex)
end
p multisplit_simple(text, separators)
["a", "", "b", "", "c"]
=> nil
p multisplit_simple(text, ['=', '!=', '=='])
["a", "", "", "b", "", "c"]
=> nil

View file

@ -0,0 +1,18 @@
def multisplit(text, separators)
sep_regex = Regexp.new(separators.collect {|sep| Regexp.escape(sep)}.join('|'))
separator_info = []
pieces = []
i = prev = 0
while i = text.index(sep_regex, i)
separator = Regexp.last_match(0)
pieces << text[prev .. i-1]
separator_info << [separator, i]
i = i + separator.length
prev = i
end
pieces << text[prev .. -1]
[pieces, separator_info]
end
p multisplit(text, separators)
# => [["a", "", "b", "", "c"], [["!=", 1], ["==", 3], ["=", 6], ["!=", 7]]]

View file

@ -0,0 +1,7 @@
def multisplit_rejoin(info)
str = info[0].zip(info[1])[0..-2].inject("") {|str, (piece, (sep, idx))| str << piece << sep}
str << info[0].last
end
p multisplit_rejoin(multisplit(text, separators)) == text
# => true