Splitting a string - looping with regular expressions

Wow. That was fast. Thanks for sharing this useful function.

I was just about to share the following which is what I managed to come up in the same time. I was going to say here are the string functions you need. Put it into some form of recursive loop and you’ll get what you need but then Renato happened!!!  :slight_smile: I am humbled!

local jsonLine = "LINE 1\n|Line 2 will be a long line of text.\n\n|LINE 3\n|Line 4 is another line of text that will appear here." local parsedStrings = {} local separatorLocation = string.find(jsonLine,"|" ) -- now we know where the first separator is print(separatorLocation) parsedStrings[1] = string.sub(jsonLine, 1, (separatorLocation - 1)) print(parsedStrings[1]) local jsonLineLength = string.len(jsonLine) jsonLine = string.sub(jsonLine, (separatorLocation + 1), jsonLineLength) print(jsonLine)

I know, seriously!  Took me more time to write the message than it did Renato to create code.   :slight_smile:

I didn’t create the code, I already had that in one of my libs due to some prior need. I got it from here: http://lua-users.org/wiki/SplitJoin

Either way, Renato, thank you so much for providing that code.  I think I looked at that site as well, but didn’t put 2 and 2 together.  So glad you knew it was what I needed.

And ksan, thank you as well for even trying to work on some code for me.  Didn’t see it until after I had started implementing the code Renato provided, but definitely appreciate it.

It did work for me.  Took me a little time to get it implemented (had trouble with finding/removing line breaks and doing some other matching, but I figured it out), and it is working great. 

Again, thank you both for your help.

Super!!! Sounds like you have a fun project. Look forward to seeing it when you release. Good luck!!!

On our side we are usually using the string.gmatch function to achieve this. I don’t know which one is faster; The split or  gmatch. Here is some sample code (you can replace the ‘|’, by comma or any other character that you use to split your sentence:
 

     local strToSplit =“DAVID\n|I need help because I really suck at regular expressions.\n\n|MIKE\n|Is this really important? Damn you and your scope creep!”

           

    for phrase in string.gmatch(strToSplit, “[^|]+”) do

         print(phrase)

    end

Thanks nmichaud.  I did end up going with Renato’s code, and it works fast enough for my app.  Would definitely recommend it for someone with a similar need.