Search code examples
regexruby

Regex / Ruby - split keeping delimiter


I need to split a string containing variables/delimiters, something like;

"Hello %Customer Name% your order number is %Order Number% and will be delivered soon"

Using;

string.split(/%/)
=> ["Hello ", "Customer Name", " your order number is ", "Order Number", " and will be delivered soon"]

Which is close to the requirement, but I'm trying to get to;

["Hello ", "%Customer Name%", " your order number is ", "%Order Number%", " and will be delivered soon"]

So essentially I need to split at % but keep it within the returned fields. I've tried a look ahead/behind with regex but cannot get it quite right.


Solution

  • You may use String#split with a pattern like

    /(%[^%]*%)/
    

    According to the documentation:

    If pattern contains groups, the respective matches will be returned in the array as well.

    See the regex demo, it matches and captures into Group 1 a % char, then any 0 or more chars other than %, and then a %.

    See a Ruby demo:

    s = "Hello %Customer Name% your order number is %Order Number% and will be delivered soon"
    p s.split(/(%[^%]*%)/)
    # => ["Hello ", "%Customer Name%", " your order number is ", "%Order Number%", " and will be delivered soon"]