Skip to content

Instantly share code, notes, and snippets.

@TApicella
Created May 16, 2017 17:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TApicella/e897a84eb419328a2ae2c18198074dd0 to your computer and use it in GitHub Desktop.
Save TApicella/e897a84eb419328a2ae2c18198074dd0 to your computer and use it in GitHub Desktop.
RosettaCode- Multisplit created by tapicella - https://repl.it/IBTP/3
'''
Task
Multisplit
You are encouraged to solve this task according to the task description, using any language you may know.
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input.
This is particularly useful when doing small parsing tasks.
The task is to write code to demonstrate this.
The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators.
The order of the separators is significant:
The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings.
Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”.
For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output.
'''
#Method- replace each previous one with the last separator
def multisplit(mystring, delimiters):
last = delimiters[-1]
for d in delimiters[0:-1]:
splitstring = mystring.split(d)
mystring = last.join(splitstring)
return mystring.split(last)
print(multisplit("a!=b=!=c", ["==", "!=", "="])) #I disagree with their suggested output so I'm going to ignore that part
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment