Friday 13 December 2013

Collapse and Capture a Repeating Pattern

This particular Stackoverflow question shows the ease of use of parse over regex. (It was so simple with parse that this post took me about 5 minutes to write :-) 

This is what the OP says:
I keep bumping into situations where I need to capture a number of tokens from a string and after countless tries I couldn't find a way to simplify the process.
This is what the input looks like:

How does parse deal with it? 

Simple. 'parse <string> none' will let you split a string by the spaces. Similarly, 'parse/all <string> "x"' will let you split a string by the character "x", whatever it might be. You can even use more characters, like "xyz", and the string will be split by them. See:

This is how we can get strings from the given situation using parse:

Usage:

OP's string

Now, the OP's string starts with "start:" and ends with ":end", and we need to factor that. There are many ways of doing this. Different people will do it differently, but this is what I'll do:

You can use a single line for lines 2 and 3. Like:

Here is another version if you don't like too many parenthesis:

Usage (same for all 3 versions of the function):

Feel free to ask or say anything.

No comments:

Post a Comment